I would like to validate the user input. For example, if I enter a character in the place of a integer, then the program should terminate.
CodePudding user response:
The simplest way to read an integer from the user with basic input validation would be the following:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int num;
printf( "Enter a number: " );
switch ( scanf( "%d", &num ) )
{
case 1:
//input is valid
break;
case 0:
printf( "That was not a valid number!\n" );
exit( EXIT_FAILURE );
default:
printf( "Unexpected input error occurred!\n" );
exit( EXIT_FAILURE );
}
printf( "You entered the following valid input: %d\n", num );
}
However, this solution is not perfect, as it will accept for example 6sdfh4q
as valid input for the number 6
, although that input should probably be rejected. This is because scanf
is not designed for line-based user input.
For line-based user input, it is probably better to use fgets
instead of scanf
. In contrast to scanf
, fgets
will generally read one line at a time, so it is the perfect function for reading user input. After reading one line of user input, you can attempt to convert the input to a number using the function strtol
or sscanf
.
Performing full input validation is rather complex in C. This is how I would write it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
int main( void )
{
char buffer[1024], *p;
long num;
//prompt user for input
printf( "Enter a number: " );
//get one line of input from input stream
if ( fgets( buffer, sizeof buffer, stdin ) == NULL )
{
fprintf( stderr, "Unrecoverable error reading from input!\n" );
exit( EXIT_FAILURE );
}
//make sure that entire line was read in (i.e. that
//the buffer was not too small)
if ( strchr( buffer, '\n' ) == NULL )
{
printf( "Line input was too long!\n" );
exit( EXIT_FAILURE );
}
//attempt to convert string to number
errno = 0;
num = strtol( buffer, &p, 10 );
if ( p == buffer )
{
printf( "Error converting string to number\n" );
exit( EXIT_FAILURE );
}
//make sure that no range error occurred
if ( errno == ERANGE )
{
printf( "Range error!\n" );
exit( EXIT_FAILURE );
}
//make sure that remainder of line contains only whitespace,
//so that input such as "6sdfh4q" gets rejected
for ( ; *p != '\0'; p )
{
if ( !isspace( (unsigned char)*p ) )
{
printf( "Unexpected input encountered!\n" );
exit( EXIT_FAILURE );
}
}
//number was successfully converted, so we print it
printf( "You entered the following valid number: %ld\n", num );
}
Example output of this program when entering a valid number:
Enter a number: 65
You entered the following valid number: 65
Example output of this program when entering invalid input:
Enter a number: 6sdfh4q
Unexpected input encountered!
CodePudding user response:
The normal way to terminate a program is to call ‘exit’ function.
exit(ERROR_CODE);