A robust get_int function


Please Click On My Sponsor. It earns me a little extra cash.

Download The Sample Code 
Return to the HOWTOs

 

The way to retrieve an integer in C is to use the scanf("%d", &intVar) command. However, this command does not guarantee that the user types in an integer, and it does no error handling. That is why in all my programs I have a function called get_int that I call whenever I need to get an integer. First lets start out by declaring our get_int function.

Put this in the prototype area:

            void get_int(int *piInput);           

Then this is the actual function:


void get_int(int *piInput)

{

	scanf("%d", piInput);

}

This is the driver to test it out:


int main(void)

{

	int iInput;



	printf("\nPlease enter an integer: ");

	get_int(&iInput);



	printf("\nYou entered: %d", iInput);



	return 0;

}

            

Ok now try entering invalid data instead of an integer, such as "hello". Does the program crash, give you invalid data, or hang. That is why we need a better get_int that can handle whatever we through at it. Ok lets get started. First you need to know a little about scanf. scanf is a standard c function. If you use the scanf function like with one % like we do, then scanf will return 1 if all goes well. We can use this as our first error checking. Here is the code:


void get_int(int *piInput)

{

	int iCheck = 0;

	int iochar = 0;



	do

	{       

		iCheck = scanf("%d", piInput);

		if (iCheck != 1)

		{

			printf("\nThat is not a valid integer statement\n");

			printf("Please try again: ");

			

			while ((iochar = getchar()) != '\n');



		}

	}

	while (iCheck < 1);

}

            

So what does this code do, well first thing we do is we just declare a couple of variables iCheck is what we will use to get the return value from scanf, iochar is just a temporary variable we use when we clean out the buffer. Then we enter our do while loop we execute this as long as iCheck is less than one. Once inside our loop we execute our scanf and store the return value in iCheck. If iCheck doesn't equal 1 then scanf didn't find a valid integer and we need to tell the user to try again. The while((iochar.... statement simply reads through every character in the buffer until it finds the newline character.  This causes every character in the buffer to be deleted. If you don't do that, then next time you call scanf you will just re-read the same garbage.

Ok this function now forces the user to enter a number, but what if they enter 2.45 or 2abc. Try it and see, in my case I get just 2. Now wouldn't it be better if we told the user they entered an invalid integer and let them try again? Thats what this code does.


void get_int(int *piInput)

{

	int iCheck = 0;

	int iochar = 0;



	do

	{       

		iCheck = scanf("%d", piInput);

		if (iCheck != 1)

		{

			printf("\nThat is not a valid integer statement\n");

			printf("Please try again: ");

			

			while ((iochar = getchar()) != '\n');



		}

		else

		{

			iochar = getchar();

			if (!isspace(iochar))

			{

				printf("\nThat is not a valid integer statement\n");

				printf("Please try again: ");

				iCheck = 0;

				while ((iochar = getchar()) != '\n');

			}

		}

	}

	while (iCheck < 1);

}

            

Before this will compile though, you must make sure you include the ctype.h header at the top of your file.

#include <ctype.h>

This will allow you to use the isspace() function. Ok the first part of this code looks the same as above. However, now if scanf returns 1 then we know it found what it thinks is an integer. Then we check to see if the next character in the buffer is a white space (tab, new line, space). If it is then we know we have an integer and we can just continue. If it isn't then we notify the user that he needs to enter a new integer, we set the iCheck variable to less than 1 so that our loop executes, and finally we clean the buffer out so that we don't re-read the garabage. 

This is it, this function will guarantee that the user enters a valid integer. If the user enters text such as "hello", or decimal digit such as 1.34 then we will tell the user the input is invalid and let them try again. Enjoy.

Download The Sample Code
Return to the HOWTOs