Reputation: 17
How do I ensure that the user inputs only an integer value so that the program wont crash?
If the user inputs anything else than an integer, I want to: printf("Please re-check your entry);
printf("How many values do you want to enter? \t");
int g;
scanf("%d", &g);
Upvotes: 1
Views: 1984
Reputation: 25865
I would like to say that you have to make some custom validation to check if whether scanf
read integer or not.
Also i advise to use fgets
(There is no bounds checking in scanf()
)
you can do something like this
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
int validate ( char *a )
{
unsigned x;
for ( x = 0; x < strlen ( a ); x++ )
if ( !isdigit ( a[x] ) ) return 1;
return 0;
}
int main ( void )
{
int i;
char buffer[BUFSIZ];
printf ( "Enter a number: " );
if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
buffer[strlen ( buffer ) - 1] = '\0';
if ( validate ( buffer ) == 0 ) {
i = atoi ( buffer );
printf ( "%d\n", i );
}
else
printf ( "Error: Input validation\n" );
}
else
printf ( "Error reading input\n" );
return 0;
}
Upvotes: 1
Reputation: 3870
Try something like this-
#include<stdio.h>
int main()
{
int num;
printf("Enter the number\n");
if((scanf("%d",&num)) == 1){ // checking return value of scanf here!
printf(": %d\n",num);
// do your stuff here
}
else
printf("Please recheck your input!\n");
return 0;
}
Here If the input is properly read and assigned scanf
will return 1, else it will return 0.
Sample output-
root@sathish1:~/My Docs/Programs# ./a.out
Enter the number
2
: 2
root@sathish1:~/My Docs/Programs# ./a.out
Enter the number
asd
Please recheck your input!
Upvotes: 0
Reputation: 35
I would say, check the return value of scanf:
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.
Upvotes: 2