Checking Input #
As mentioned in the previous section on Input and Output, the scanf function returns a value that tells us how many items it correctly read in from the keyboard. This can be important because if a variable is not read in correctly, its value may be undefined and cause strange behavior in your program.
As we may be working with safety critical systems we need to ensure that the values of our input is actually input by the user.
Here we have an naive piece of code that doesn’t check the value entered by the user:
int num;
printf("Please enter a number: ");
scanf("%d",&num);
printf("The number you entered was: %d", num);
If the user enters five, something that doesn’t match the input pattern, (an integer, %d), it won’t put that into the variable num. The value of num then will be undefined, and accessing the value of an undefined variable is undefined behavior. We need to avoid undefined behavior in our program.
We can capture the return value of scanf in a variable and use an if statement to check if our input went as planned, if num_readings doesn’t have the correct value, in this case 1, we know the input is incorrect:
int num;
int num_readings;
printf("Please enter a number: ");
num_readings = scanf("%d",&num);
if(num_readings != 1)
{
printf("Invalid Input. Exiting.");
return 0;
}
printf("The number you entered was: %d", num);
If the user enters something that isn’t an integer, the program prints a message saying the input is invalid and then exits. This is fairly abrupt, but it is the best that we can do at this point. When we move on to looping we will revisit this and formulate a more user friendly solution.