473,396 Members | 1,726 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

making sure only integer is input

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.
Nov 19 '05 #1
8 20974
On 2005-11-19, Radith <ra****@xtra.co.nz> 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.


Don't use scanf in that way.
Nov 19 '05 #2
Jordan Abel wrote:
On 2005-11-19, Radith <ra****@xtra.co.nz> 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.


Don't use scanf in that way.


or still use scanf since he is a biginner and check the return value
and provide a appropiate prompt before excepting input again. Nothing
wrong with using scanf as long as you use it correctly.

while (scanf("%d",&num) !=1)/*while not input looking for*/
while( (getchar() !='\n') ); /*eat garbege in stdin that scanf
has*/
puts("puts please enter an integer");/*prompt for proper input*/

Nov 19 '05 #3
Try to deal every input as a string.if it is a num,change it into the
number.
or fflush(stdin); after your scanf(...)
just like:

int a;
while(scanf("%d",&a)!=1)fflush(stdin);

Nov 19 '05 #4
vire wrote:
Try to deal every input as a string.if it is a num,change it into the
number.
or fflush(stdin); after your scanf(...)
just like:

int a;
while(scanf("%d",&a)!=1)fflush(stdin);


Do *not* use fflush(stdin). It's not just nonstandard, it's completely
undefined. See http://www.eskimo.com/~scs/C-faq/q12.26.html. Write code
that doesn't need such tricks instead.

S.
Nov 19 '05 #5
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.
Nov 19 '05 #6
On Sat, 19 Nov 2005 14:52:53 +1300, in comp.lang.c , "Radith"
<ra****@xtra.co.nz> 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.


Yes, if you're using scanf. Don't do that. The FAQ has some hints
about why not to use scanf.

Use fgets, parse the string to see if its a number, then handle
appropriately.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 19 '05 #7
Simon Biber wrote:
Radith wrote:
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??


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.

Just because I'm feeling mean, I'll point out that the code listed above
does the wrong thing when presented with the output of either of the
programs listed below.

#include <stdio.h>
int main(void)
{
printf("%*s99\n", 99, "");
return 0;
}
#include <stdio.h>
int main(void)
{
printf("\n");
return 0;
}
Rob
Nov 23 '05 #8
Rob Adams wrote:
Simon Biber wrote:
Radith wrote:
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??


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.
[snip]
If the number returned by this function is negative, some
unrecoverable error occurred.


Just because I'm feeling mean, I'll point out that the code listed above
does the wrong thing when presented with the output of either of the
programs listed below.

#include <stdio.h>
int main(void)
{
printf("%*s99\n", 99, "");
return 0;
}
#include <stdio.h>
int main(void)
{
printf("\n");
return 0;
}


Good catches. I think this solves the problems.

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;
}
else /* no newline found */
{
int ch;
/* read and discard the rest of the line */
while((ch = getchar()) != EOF && ch != '\n');
if(ch == EOF) break;
printf("Line too long, try again: ");
fflush(stdout);
continue;
}

if(buf[0] == 0) /* empty line */
{
printf("Empty line not acceptable, try again: ");
fflush(stdout);
continue;
}

/* check if input contains only digits */
if(strspn(buf, "0123456789") == strlen(buf))
{
long result;
errno = 0;

/* if no conversion error, then return */
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;
}

--
Simon.
Nov 23 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Paul E Collins | last post by:
Given a string variable (form input), how can I determine whether it represents a valid integer? is_numeric is true for floats as well as integers, and is_int always fails on a string. P.
2
by: Stewart | last post by:
Originally posted in comp.lang.javascript: Newsgroups: comp.lang.javascript From: "Stewart" Date: 23 Aug 2005 02:50:04 -0700 Local: Tues, Aug 23 2005 10:50 am Subject: FireFox, RemoveChild,...
19
by: Christian Fowler | last post by:
I have a VERY LARGE pile of geographic data that I am importing into a database (db of choice is postgres, though may hop to oracle if necessary). The data is strictly hierarchical - each node has...
351
by: CBFalconer | last post by:
We often find hidden, and totally unnecessary, assumptions being made in code. The following leans heavily on one particular example, which happens to be in C. However similar things can (and...
8
by: Candace | last post by:
I am using the following code to pick off each digit of a number, from right to left. The number I am working with is 84357. So for the first iteration it should return the number 7 and for the...
1
by: redpayne | last post by:
Okay, I finally got this program to run according to what the book had us build it as. Now prof wants case 2 and case 3 to prompt again for input, check input to see if it is the correct type, then...
10
by: JurgenvonOerthel | last post by:
Consider the classes Base, Derived1 and Derived2. Both Derived1 and Derived2 derive publicly from Base. Given a 'const Base &input' I want to initialize a 'const Derived1 &output'. If the...
10
by: Jason | last post by:
I'm making a program that will convert decimal inputs (in this case, in inches) and output a fractional answer. At the moment, I'm only able to output the fractional answer in three parts: A whole...
4
by: crochunter | last post by:
Hi, I want to read values from a text files from specified fields and use them as values to fill my methods inside the paintComponent() method. I am using for loop to do that but not able to do it...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.