When processing text data , either from a text file or input entered via the keyboard, we sometimes need to check the data to see if it’s an integer first, then use it for processing.
Note: All code in this example can be downloaded here
Logical error…
In this example, we ask our user to enter a valid integer and we output the square of the integer:
/*
we ask our user to enter a valid integer
and we output the square of the integer
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int inputInteger; //string used to store user input
int inputSquared;// used to store the square of a valid integer.
printf("Enter an Integer value....\n");
scanf("\n%d",&inputInteger);//get input from user
printf("You entered : %d\n", inputInteger);
inputSquared = inputInteger*inputInteger;//find square
printf("\n%d squared is %d\n",inputInteger, inputSquared);
printf("\nSuccess! Exiting program\n");
return 0;
}
This code works when we enter valid input , in this case the user enters 12:

However, if the user enters alpha text data, we get strange results:

A simple fix…
To fix this issue we adhere to 2 rules:
- Read all text data as character strings, and then
- use the atoi(…) function to convert the string to a valid integer
The previous example can be fixed by using the rules above applied to the current situation:
- Read all text data as character strings, and then
- use the atoi(…) function to TRY to convert the string to a valid integer
- If the user had entered alpha text data, generate an error message, prompt the user to re-enter the data, and go to step 1, otherwise :
- Calculate the valid output.
Below is the code…
/*
this programs shows how to validate user input as integers.
if the user enters a valid integer, we output the square of the integer,
otherwise we output an error message and prompt the user to re enter a valid integer
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h> //in order touse true and false
int main()
{
char input[50]; //string used to store user input
int inputAsAnInteger;//used store the converted input as an integer
int inputSquared;// used to store the square of a valid integer.
while(true)//loop 'infinitely'
{
printf("Enter an Integer value....\n");
scanf("%s",&input);//get input from user
printf("You entered : %s\n", input);
inputAsAnInteger=atoi(input);//convert input to integer
if (inputAsAnInteger==0)//if the input is not a number......
{
printf("Invalid input entered\n\n");
}
else//input is a number
{
inputSquared = inputAsAnInteger*inputAsAnInteger;//find square
printf("\n%d squared is %d\n",inputAsAnInteger, inputSquared);
printf("\nSuccess! Exiting program\n");
break;//exit 'infinite' loop.
}
}
return 0;
}
And a sample run shown below with invalid input and valid input:

However, note that atoi(…) returns 0 when 0 is entered or invalid input entered, an edge case which produces erroneous results:

Fixing the fix…
This problem can be solved by checking every digit in the input string to see if they are all digits, before converting to string. In this way, we cater for a correct result if the text data “0” is entered.
Our rules to fix the problem now becomes:
- Read all text data as character strings, and then
- Check eack character of the string to ensure they’re all digits, then
- use the atoi(…) function to convert the string to a valid integer
This code uses a function which performs that check:
/*
this programs shows how to validate user input as integers.
if the user enters a valid integer, we output the square of the integer,
otherwise we output an error message and prompt the user to re enter a valid integer
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h> //in order to use true and false
#include <ctype.h> // in order to use the isdigit function.
bool isNumber(char* stringArray);
int main()
{
char input[50]; //string used to store user input
int inputAsAnInteger;//used store the converted input as an integer
int inputSquared;// used to store the square of a valid integer.
while(true)//loop 'infinitely'
{
printf("Enter an Integer value....\n");
scanf("%s",&input);//get input from user
printf("You entered : %s\n", input);
if (!isNumber(input))//if the input is not a number......
{
printf("Invalid input entered\n\n");
}
else//input is a number
{
inputAsAnInteger=atoi(input);//convert input to integer
inputSquared = inputAsAnInteger*inputAsAnInteger;//find square
printf("\n%d squared is %d\n",inputAsAnInteger, inputSquared);
printf("\nSuccess! Exiting program\n");
break;//exit 'infinite' loop.
}
}
return 0;
}
bool isNumber(char* stringArray)
{
//go through each character
//location in the array until
//we reach the null character (end of input)
for (int i = 0; stringArray[i]!='\000'; i++)
{
if(isdigit(stringArray[i])==0)//if the current character is not a digit....
return false; //return false and end function here
}
return true;//return true since the entire array contained numeric characters
}
Now, we get correct results in all cases:

Conclusion And Thoughts
The basic strategy for checking for integer input, is to read all input as text and use the atoi(…) function to try converting the input whilst performing error checking.
To best understand the coded examples, I insist that you use the data in the sample runs to :
- perform a dry run as well as
- step through each line of code by running the code in debug mode .
The examples above contain minimal explanation, is intended pre-class preparation and presentation in our classroom where we can have a broader discussion and I can answer any questions that you may have.
© 2020 Vedesh Kungebeharry. All rights reserved.