#include \"stdafx.h\"
#include
void main()
{
char buffer[20];
int num;
printf(\"Please enter a number\\n\");
fgets(buffer, 20, std
atoi
is not suitable for error checking. Use strtol
or strtoul
instead.
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
long int result;
char *pend;
errno = 0;
result = strtol (buffer, &pend, 10);
if (result == LONG_MIN && errno != 0)
{
/* Underflow. */
}
if (result == LONG_MAX && errno != 0)
{
/* Overflow. */
}
if (*pend != '\0')
{
/* Integer followed by some stuff (floating-point number for instance). */
}
There is the isdigit
function that can help you check each character:
#include <ctype.h>
/* ... */
for (i=0; buffer[i]; i++) {
if (!isdigit(buffer[i])) {
printf("Bad\n");
break;
}
}