I want the program to ask the user for a number, and if the user does not enter a number the program will say "input not a integer."
Thx for the help guys!
I want the program to ask the user for a number, and if the user does not enter a number the program will say "input not a integer."
Thx for the help guys!
I propose this (it doesn't handle integer overflow):
#include <stdio.h>
int main(void)
{
char buffer[20] = {0}; // 20 is arbitrary;
int n; char c;
while (fgets(buffer, sizeof buffer, stdin) != NULL)
{
if (sscanf(buffer, "%d %c", &n, &c) == 1)
break;
else
printf("Input not integer. Retry: ");
}
printf("Integer chosen: %d\n", n);
return 0;
}
EDIT: Agreed with chux suggestions below!
One possible way: use scanf()
function to read the input. It returns the number of items it successfully read.
Another way: read the input as string with scanf()
of fgets()
and then try to parse it as integer.