473,382 Members | 1,355 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,382 software developers and data experts.

using scanf() in while loop

Hello,

I used scanf() in a while loop, which ensures that user input is
valid (must be an integer no greater than 21 or less than 3).
If user enters a number out of the range, or enters non-number,
he/she will be asked to retry.

/* start */

int n;

while(1){
printf("Please enter an integer (3 <= x <= 21): \n");
if(scanf("%d", &n) && (n >= 3) && (n <= 21)){
return n;
}
printf("The input must be a number within the (3, 21) range,
inclusive. Please retry.\n"); //Point A
}

/* End */

In the above code, the first condition (scanf("%d", &n))
tests whether user inputs a number. In my tests, since
the format specifier is %d, my take is that if user enters
anything other than an integer, scanf() will not modify n,
and will by itself return 0 indicating reading data has failed
as a result of type mismatch.

My problem is that when user inputs something other than
an integer, the scanf() never runs again, and this while loop
continues indefinitely.

Weirdly, if I input an integer out of the (3,21) boundary,
it runs correctly and re-prompts me for a new value.

Any opinion is welcome. Thanks in advance

Mar 1 '06 #1
6 26177
obdict wrote:
Hello,

I used scanf() in a while loop, which ensures that user input is
valid (must be an integer no greater than 21 or less than 3).
If user enters a number out of the range, or enters non-number,
he/she will be asked to retry.

/* start */

int n;

while(1){
printf("Please enter an integer (3 <= x <= 21): \n");
if(scanf("%d", &n) && (n >= 3) && (n <= 21)){
return n;
}
printf("The input must be a number within the (3, 21) range,
inclusive. Please retry.\n"); //Point A
}

/* End */

In the above code, the first condition (scanf("%d", &n))
tests whether user inputs a number. In my tests, since
the format specifier is %d, my take is that if user enters
anything other than an integer, scanf() will not modify n,
and will by itself return 0 indicating reading data has failed
as a result of type mismatch.

My problem is that when user inputs something other than
an integer, the scanf() never runs again, and this while loop
continues indefinitely.
scanf() in fact does run again. The problem is that it sees data that
doesn't match your format string sitting on stdin, and thus returns
without touching it. You never take this data off the stream, and so
scanf() just keeps failing. To get around this, one solution is to read
the garbage data off of stdin:

int ch;
while((ch = getchar()) != '\n' && ch != EOF);

Although a better solution may be to not use scanf() at all. You should
also change your scanf() comparison, perhaps to == 1. If scanf() fails
because of end of file, it will return EOF which is negative, and your
current program will interpret this as a successful read.

Hope that helps,

--John

Weirdly, if I input an integer out of the (3,21) boundary,
it runs correctly and re-prompts me for a new value.

Any opinion is welcome. Thanks in advance


Mar 1 '06 #2
That really helped. Thanks a lot, John!

Mar 1 '06 #3
In my view writing such code is not usefull at all. It is consfusing
as well as incorrect. So it is better to devide the range checking and
user input for better clarity of the logic. Though it is always your
wish. Also a character is an number if you see its Ascii equivalent. So
the logic you want to have it invalid in the case of character also.

Mar 1 '06 #4

ab*********@gmail.com wrote:
In my view writing such code is not usefull at all. It is consfusing
as well as incorrect.
What code? I see no code, and no code is correct code.
So it is better to devide the range checking and
user input for better clarity of the logic.
Indeed, but how is this related to C?
Also a character is an number if you see its Ascii equivalent.
No it is not, at least not in C. And what about EBCDIC?
So
the logic you want to have it invalid in the case of character also.


Now I'm really confused.

Advice (do follow it in this group):

- quote what and who you're replying to (if using Google, click on Show
Options, and then on Reply that appears below the headers)
- don't top post
- stay on topic (which is Standard C as defined by ISO)

--
BR, Vladimir

Mar 1 '06 #5

"obdict" <ha******@gmail.com> wrote in message
news:11**********************@i39g2000cwa.googlegr oups.com...
Hello,

I used scanf() in a while loop, which ensures that user input is
valid (must be an integer no greater than 21 or less than 3).
If user enters a number out of the range, or enters non-number,
he/she will be asked to retry.

/* start */

int n;

while(1){
printf("Please enter an integer (3 <= x <= 21): \n");
if(scanf("%d", &n) && (n >= 3) && (n <= 21)){
return n;
}
printf("The input must be a number within the (3, 21) range,
inclusive. Please retry.\n"); //Point A
}

/* End */

In the above code, the first condition (scanf("%d", &n))
tests whether user inputs a number. In my tests, since
the format specifier is %d, my take is that if user enters
anything other than an integer, scanf() will not modify n,
and will by itself return 0 indicating reading data has failed
as a result of type mismatch.
Not true. For example, if the user enters "123xyz", n will be assigned a
value of 123, the input scan will stop when the "x" is encountered and scanf
will return a value of 3. Subsequent scanf will all fail, each time trying
to read "x".

Best bet is not to use scanf for input. Use fgets instead.

My problem is that when user inputs something other than
an integer, the scanf() never runs again, and this while loop
continues indefinitely.

Weirdly, if I input an integer out of the (3,21) boundary,
it runs correctly and re-prompts me for a new value.

Any opinion is welcome. Thanks in advance


--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project
Mar 1 '06 #6
Fred Kleinschmidt wrote:
"obdict" <ha******@gmail.com> wrote in message
news:11**********************@i39g2000cwa.googlegr oups.com...

while(1){
printf("Please enter an integer (3 <= x <= 21): \n");
if(scanf("%d", &n) && (n >= 3) && (n <= 21)){
return n;
}
printf("The input must be a number within the (3, 21) range,
inclusive. Please retry.\n"); //Point A
}
For example, if the user enters "123xyz", n will be assigned a
value of 123, the input scan will stop when the "x" is encountered and scanf

^^^^^ will return a value of 3. Subsequent scanf will all fail, each time trying ^^^^^^^^^^^^^^^^^^^^^^^^ to read "x".


Not exactly true either :)

<quote src="man 3 scanf">
RETURN VALUE
[...] If an error or end-of-file occurs after conversion has
begun, the number of conversions which were successfully
completed is returned.
</quote>
tmp$ cat foo.c
#include <stdio.h>

int main(void) {
int m, n=0;
m = scanf("%d", &n);
printf("Value read: %d\n", n);
printf("Value returned: %d\n", m);
return 0;
}

tmp$ gcc -W -Wall -Werror -std=c89 -pedantic -O2 foo.c -ofoo
tmp$ echo "123xyz" | ./foo
Value read: 123
Value returned: 1

--
If you're posting through Google read <http://cfaj.freeshell.org/google>
Mar 2 '06 #7

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

Similar topics

13
by: Kris | last post by:
Hi! I have the following instruction: char wyp; scanf("%c",&wyp); this scanf is in a while loop, and I want it to get EXACTLY one character each time. Does anyone knows how to do it? BTW....
7
by: Przemo Drochomirecki | last post by:
hi, SCANF is not well described in my books, i'd like to do this stuff: 1) read all numbers from a line, separated by #32 2) read all numbers from a line, separaed by ',' 3) read whole line ...
6
by: hpy_awad | last post by:
I am writing stings ((*cust).name),((*cust).address)to a file using fgets but rabish is being wrote to that file ? Look to my source please and help me finding the reason why this rabish is being...
185
by: Martin Jørgensen | last post by:
Hi, Consider: ------------ char stringinput ..bla. bla. bla. do {
3
by: cachaco87 | last post by:
Hi, I'm new to this boards, and I need some help finishing a project for school. Im using nested if-statements inside a while loop to execute different actions. action C consist of printing the...
12
by: wuzertheloser | last post by:
I need help with Taylor Series Part A: Scan the angle in degrees x_deg. Express this angle in radians by using x=PI*x_deg/180, and calculate Y=cos^2(x) by using the math.h...
8
by: Neil | last post by:
Hello Just to let you know this not homework, I'm learning the language of C on my own time.. I recently tried to create a escape for user saying printf ("Do you want to continue? (y or n)");...
8
by: Army1987 | last post by:
Is this a good way to discard unread data after scanf()? while (getchar() != '\n') ; According to the FAQ scanf always leaves the trailing newline on the input stream, so there's no risk of...
6
by: akk003 | last post by:
Hello I'am a returning coder to C programming language and would appreciate if you could help me understand why does my while loop behave normally in the following code: int loop = 1; char...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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?
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...

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.