If you want to see whether scanf
was able to successfully match an integer, you must check the return value.
Change the line
scanf("%d", &NewWorkder->id);
to:
if ( scanf("%d", &NewWorkder->id) != 1 )
{
fprintf( stderr, "Error reading number!\n" );
exit( EXIT_FAILURE );
}
If you want to check whether the value is in the desired range, you can add the following code:
if ( newWorker->id < 0 || newWorker->id > 100 ) )
{
fprintf( stderr, "Input is out of range!\n" );
exit( EXIT_FAILURE );
}
If you don't want your program to exit on bad input, but would prefer it to print an error message and prompt the user again, you could use the following code instead:
bool bad_input;
do
{
bad_input = false;
//prompt user for input
printf("Enter ID: ");
//call scanf and verify that function was successful
if ( scanf("%d", &NewWorkder->id) != 1 )
{
printf( "Error reading number, try again!\n" );
bad_input = true;
}
//verify that input is in range
if ( newWorker->id < 0 || newWorker->id > 100 ) )
{
printf( "Number must be between 0 and 100, try again!\n" );
bad_input = true;
}
//discard remainder of line
for ( int c; (c=getchar()) != EOF && c != '\n'; )
;
} while ( bad_input );
However, for line-based input, I wouldn't recommend using scanf
, because that function does not extract the entire line from the input stream; it only extracts as much as it needs. This can be confusing and can lead to programming bugs. Instead, I would recommend using fgets
and strtol
instead. See the other answer for such a solution. Also, I suggest that you read this guide: A beginners' guide away from scanf()