Read your input as text using either scanf
with a %s
conversion specifier or by using fgets
, then use the strtol
library function to do the conversion:
#define MAX_DIGITS 20 // maximum number of decimal digits in a 64-bit integer
int val;
int okay = 0;
do
{
char input[MAX_DIGITS+2]; // +1 for sign, +1 for 0 terminator
printf("Gimme a number: ");
fflush(stdout);
if (fgets(input, sizeof input, stdin))
{
char *chk = NULL; // points to the first character *not* converted by strtol
val = (int) strtol(input, &chk, 10);
if (isspace(*chk) || *chk == 0)
{
// input was a valid integer string, we're done
okay = 1;
}
else
{
printf("\"%s\" is not a valid integer string, try again.\n", input);
}
}
} while (!okay);