0

This is what I think the code should look like. It's inside a function (main) by the way.

char a;
if (a [is detected]) {
    printf("Incorrect input format \n");
    exit( EXIT_FAILURE );
}    
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
answerSeeker
  • 2,692
  • 4
  • 38
  • 76

2 Answers2

3

Remember that digits are also characters. What you want to do is to use scanf to scan for an integer, and check the return value. The return value from the scanf family of function is the number of successfully scanned items, or -1 on error. If you scan for a single integer (format "%d") then if scanf doesn't return 1 there was an error.

So you could do something like

if (scanf(" %d", &number) == 1)
{
    /* Got a number okay */
}
else
{
    /* Not a number in the input */
}

Also remember that if scanf fails, the input is still there, so you can't just loop and hope the current input will be disregarded. A simply way to get by that is to use fgets to read one line of input, and then use sscanf to scan the newly read line.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Use fread instead of scanf to read the input from stdin. Parse the input provided by user to check if char is given as input, then print the error.

0xF1
  • 6,046
  • 2
  • 27
  • 50