Enhancing the Program
Let's enhance our program to make it more user-friendly and robust. We'll add a loop so the user can check multiple numbers without restarting the program, and we'll also add input validation.
Update your main.c
file with the following code:
#include <stdio.h>
#include <string.h>
#include <ctype.h> // For isdigit function
int main() {
char number[20];
int flag, i;
char choice;
do {
flag = 0; // Reset flag for each iteration
// Prompt the user to enter a number
printf("\nEnter a number: ");
scanf("%s", number);
// Input validation - check if the input contains only digits and at most one decimal point
int valid = 1;
int decimal_count = 0;
for(i = 0; number[i] != '\0'; i++) {
if(number[i] == '.') {
decimal_count++;
if(decimal_count > 1) {
valid = 0;
break;
}
} else if(!isdigit(number[i])) {
valid = 0;
break;
}
}
if(!valid) {
printf("Invalid input! Please enter a valid number.\n");
continue;
}
// Check if the number is integer or float
for(i = 0; number[i] != '\0'; i++) {
if(number[i] == '.') {
flag = 1;
break;
}
}
// Display the result
if(flag) {
printf("The entered number is a floating point number.\n");
} else {
printf("The entered number is an integer number.\n");
}
// Ask if the user wants to continue
printf("\nDo you want to check another number? (y/n): ");
scanf(" %c", &choice);
} while(choice == 'y' || choice == 'Y');
printf("\nThank you for using the program!\n");
return 0;
}
This enhanced version includes:
- A
do-while
loop that allows the user to check multiple numbers.
- Input validation to ensure that the input contains only digits and at most one decimal point.
- A more user-friendly interface with clearer prompts and feedback.
Compile and run this enhanced version:
cd ~/project
gcc main.c -o main
./main
Test it with various inputs, including:
- Integer numbers like
42
- Floating-point numbers like
3.14
- Invalid inputs like
abc
or 1.2.3
The program should appropriately handle all these cases and allow you to continue checking numbers until you choose to exit.