0

How could I generate an error message when e.g. 'a' is the input value?

#include <stdio.h>
    
int main ( void )
{
    int a; 
    scanf ("%d" , & a) ;
    
    // if a is not a number, then generate error
    
    return 0 ;
}
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
Marcos Gonzalez
  • 1,086
  • 2
  • 12
  • 19

1 Answers1

4

You want to make sure that scanf actually correctly recognized an integer, so check the return value. The scanf family of functions returns an integer representing the number of correctly parsed elements, so if you do scanf("%d", ...) you should expect a return value of 1 in case of a valid integer:

int a;

if (scanf("%d", &a) != 1) {
    // the value read was not an integer, the end of file was reached, or some other error occurred
} else {
    // good
}

This is all you can do with scanf, however note that this is sadly not enough to ensure that the scanned value is indeed the actual value entered by the user, and that it has not overflowed.

The only sane way in which you can do this in C is through first getting the input as a string, and then parsing it using strtol or similar functions, which are able to correctly report parsing and overflow errors.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • Be aware, `scanf( "%d", &a)` will accept an input like `"12c"` - it will successfully convert and assign `12` to `a` and leave `'c'` in the input stream to foul up the next read. You need to check both the return value of `scanf` *and* you need to check the first character that was *not* converted - if it isn't whitespace, then you don't have a valid integer input. – John Bode Mar 03 '21 at 18:43