473,545 Members | 2,686 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 26226
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*********@gma il.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.goo glegroups.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.goo glegroups.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
3072
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. How can I get information how many characters were entered and assigned to variable wyp?
7
19944
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 thx in adv.
6
3481
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 written. /* Book name : File name : E:\programs\cpp\iti01\ch10\ex09_5p1.cpp Program discription: Adding name,Address to...
185
17243
by: Martin Jørgensen | last post by:
Hi, Consider: ------------ char stringinput ..bla. bla. bla. do {
3
3135
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 number of times a person executed action A and action B. For that a declared variables intCounterB and intCounterC, and included the...
12
39134
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 library of functions (pow() and cos() functions). Compare the so calculated value of Y=cos^2(x) with the approximate value y obtained by using...
8
2362
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)"); The scanf statement follows the prompt(printf above) which is the last statement in the while loop, before the "}"
8
5133
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 discarding any more than needed. (In the best case, when scanf() correctly works and the user hasn't input spurious data beside those required in the...
6
8751
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 userIN; while(loop) { printf("\nIf you want to retrieve tuples prompt y/n: \t"); //items_read = scanf("%s",&userIN);
0
7496
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7428
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7685
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7941
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7452
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6014
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
1916
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1039
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
738
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.