#include "stdafx.h"
#include <stdlib.h>
void main()
{
char buffer[20];
int num;
printf("Please enter a number\n");
fgets(buffer, 20, stdin);
num = atoi(buffer);
if(num == '\0')
{
printf("Error Message!");
}
else
{
printf("\n\nThe number entered is %d", num);
}
getchar();
}
The above code accepts a number in the form of a string and converts it to integer using atoi. If the user inputs a decimal number, only the bit before the decimal is accepted. Moreover, if the user enters a letter, it returns 0.
Now, I have two queries:
i) I want the program to detect if the user entered a number with decimal point and output an error message. I don't want it to take the part before the decimal point. I want it to recognize that the input is invalid.
ii) If atoi returns 0 in case there are letters, how can I validate it since the user can enter the number 0 as well?
Thanks.