Re: making sure only integer is input
- From: Simon Biber <news@xxxxxxxxx>
- Date: Sat, 19 Nov 2005 16:03:28 +1100
Radith wrote:
Hi All,
I have a number guessing game in which users try to guess a random number. Obviously, input is required of type int.
BUT, when a user inputs a string the program will result in an undesired infinite loop.
Now, I know a string is not what we're after but in terms of error-handling; How can we prevent users from entering a string?
and if we can't do that:
How can we make sure if a string is entered, it is realized and discarded. Implying, that the user is warned about the mistake and prompted again in hope of correct input this time??
I have not included my program here because it is unncessarily large (still a begginer), but if y'all want; more than happy to attach it.
Thanks for all your time in advance.
Here's a function that demonstrates one safe way to read in an integer, and reject invalid input. It reads a line of text and then checks whether it consists solely of digits. If so, it is converted to an integer and if there was no error, the integer is returned. Otherwise, another line is read, and so on.
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h>
long read_integer(void)
{
/* declare a buffer for holding the input line */
char buf[100] = ""; /* output the initial prompt */
printf("Enter an integer: ");
fflush(stdout); /* while the user inputs a line of text */
while(fgets(buf, sizeof buf, stdin))
{
/* Remove the newline character from the buffer */
char *p = strchr(buf, '\n');
if(p) *p = 0; /* check if input contains only digits */
if(strspn(buf, "0123456789") == strlen(buf))
{
long result;
errno = 0; /* if no conversion error, then break */
result = strtol(buf, 0, 10);
if(errno == 0)
return result;
} /* Otherwise, output another prompt */
printf("Invalid input, try again: ");
fflush(stdout);
} if(feof(stdin))
{
printf("End of file reached\n");
return -1;
} printf("Error reading input\n");
return -2;
}If the number returned by this function is negative, some unrecoverable error occurred.
-- Simon. .
- Follow-Ups:
- Re: making sure only integer is input
- From: Rob Adams
- Re: making sure only integer is input
- References:
- making sure only integer is input
- From: Radith
- making sure only integer is input
- Prev by Date: Re: Reboot a PC with C code
- Next by Date: Re: convert infix to postfix
- Previous by thread: Re: making sure only integer is input
- Next by thread: Re: making sure only integer is input
- Index(es):
Relevant Pages
|
Loading