473,396 Members | 1,864 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.

help with infinite loops and scanf

Rob
I'm stuck in a program I'm making. I'm supposed to have a menu that
asks the user to choose an option between 1 and 3. If the user chooses
a valid option, i.e. types a number from 1 to 3, then appropriate
things happen for the option they chose. After each option is
executed, the menu should come back asking them to choose an option
again. It should loop and do this forever. My problem is, I have to
detect the user entering anything other than the integers 1, 2 and 3,
and it's not working.

My program isn't handling invalid input correctly. If the user enters
"1abc", then it treats that as if they had just entered the number 1,
which is incorrect. If they enter valid input of 1, 2 or 3, then it
works. If they enter a string such as "abc" as input, then I get an
infinite loop where my menu is printed over and over. I'm not sure how
to fix this. Here's my code so far. Thanks for any help.
int option;

while (1) {
printf("choose an option [1-3]: ");
scanf("%d", &option);

if (option != 1 || option != 2 || option != 3) {
printf("\nInvalid option.\n");
} else if (option == 1) {
/* do something */
} else if (option == 2) {
/* do something */
} else if (option == 3) {
/* do something */
}
}
Nov 13 '05 #1
7 7231
ak
On 26 Jul 2003 13:03:17 -0700, rm*******@yahoo.com (Rob) wrote:

|I'm stuck in a program I'm making. I'm supposed to have a menu that
|asks the user to choose an option between 1 and 3. If the user chooses
|a valid option, i.e. types a number from 1 to 3, then appropriate
|things happen for the option they chose. After each option is
|executed, the menu should come back asking them to choose an option
|again. It should loop and do this forever. My problem is, I have to
|detect the user entering anything other than the integers 1, 2 and 3,
|and it's not working.
|
|My program isn't handling invalid input correctly. If the user enters
|"1abc", then it treats that as if they had just entered the number 1,
|which is incorrect. If they enter valid input of 1, 2 or 3, then it
|works. If they enter a string such as "abc" as input, then I get an
|infinite loop where my menu is printed over and over. I'm not sure how
|to fix this. Here's my code so far. Thanks for any help.
|

try using some other input function than scanf();
for instance fgets( ), since you then have more
control on the input.

after reading the string with fgets you can parse
it by using for instance strtok()

use a switch statement instead of several if -else's
a bit more readable when there are many if-else's
hth/ak
--
g a n d a l f @ p c . n u
Nov 13 '05 #2

"Rob" <rm*******@yahoo.com> wrote in message news:9d************************@posting.google.com ...
I'm stuck in a program I'm making. I'm supposed to have a menu that
asks the user to choose an option between 1 and 3. If the user chooses
a valid option, i.e. types a number from 1 to 3, then appropriate
things happen for the option they chose. After each option is
executed, the menu should come back asking them to choose an option
again. It should loop and do this forever. My problem is, I have to
detect the user entering anything other than the integers 1, 2 and 3,
and it's not working.

My program isn't handling invalid input correctly. If the user enters
"1abc", then it treats that as if they had just entered the number 1,
which is incorrect. If they enter valid input of 1, 2 or 3, then it
works. If they enter a string such as "abc" as input, then I get an
infinite loop where my menu is printed over and over. I'm not sure how
to fix this. Here's my code so far. Thanks for any help.
int option;

while (1) {
printf("choose an option [1-3]: ");
You can flush the stdin each time to prevent the looping problem.

Add the line here:
fflush(stdin);
scanf("%d", &option);

if (option != 1 || option != 2 || option != 3) {
printf("\nInvalid option.\n");
} else if (option == 1) {
/* do something */
} else if (option == 2) {
/* do something */
} else if (option == 3) {
/* do something */
}
First, you shouldn't use OR in the first "if" line, I think there is a logical problem. You can use
AND

if (option != 1 && option != 2 && option != 3)

or even better:

if (option == 1) {
/* do something */
} else if (option == 2) {
/* do something */
} else if (option == 3) {
/* do something */
}else
printf("\nInvalid option.\n");

or using switch.
}


--
BC
Nov 13 '05 #3
Rob wrote:
My problem is, I have to detect the user entering anything other than the
integers 1, 2 and 3,
if (option != 1 || option != 2 || option != 3) {
printf("\nInvalid option.\n");
}

change line above to

if (option < 0 || option >3) {
printf("\nInvalid option.\n");
}
Nov 13 '05 #4
In 'comp.lang.c', "Burne C" <no****@notexist.com> wrote:
You can flush the stdin each time to prevent the looping problem.

Add the line here:
fflush(stdin);


No. fflush () is only defined for output streams.

--
-ed- em**********@noos.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
<blank line>
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 13 '05 #5
ak
On Sun, 27 Jul 2003 09:15:44 +0000 (UTC), amanayin <ng******@netscape.net>
wrote:

|Rob wrote:
|
|
| My problem is, I have to detect the user entering anything other than the
|integers 1, 2 and 3,
|
|
|if (option != 1 || option != 2 || option != 3) {
| printf("\nInvalid option.\n");
| }
|
|change line above to
|
|if (option < 0 || option >3) {
| printf("\nInvalid option.\n");
| }

yes well if you read the input into a string buffer pszBuf
using fgets

then you can extract the contents by using sscanf or
any other parsing function:

sscanf( pszBuf, "%d", &option );

you have to add some error handling around it though like
check return value of sscanf to see if an integer was read.

hth
/ak

--
g a n d a l f @ p c . n u
Nov 13 '05 #6
rm*******@yahoo.com (Rob) wrote in message news:<9d************************@posting.google.co m>...

My program isn't handling invalid input correctly. If the user enters
"1abc", then it treats that as if they had just entered the number 1,
which is incorrect.
By "incorrect," i assume that you mean "not as I intend." To guard
against something like "1abc", you might use

int option, count, length;
char buffer[100];
...
fgets (buffer, 100, stdin); /* DO NOT use gets(buffer); */
count = sscanf(buffer, "%d%n", &option, &length);
if (count == 1 && length < strlen(buffer))
/* there were extra characters after the number */

This is oversimplified, of course, because you'll have to deal with
EOF, the '\n', and possible trailing whitespace, but you get the idea.
If they enter valid input of 1, 2 or 3, then it
works. If they enter a string such as "abc" as input, then I get an
infinite loop where my menu is printed over and over.
See <http://www.eskimo.com/~scs/C-faq/q12.19.html>.
I'm not sure how
to fix this. Here's my code so far. Thanks for any help.
int option;

while (1) {
printf("choose an option [1-3]: ");
scanf("%d", &option);

<snip>

Read <http://www.eskimo.com/~scs/C-faq/q12.20.html> for why you should
forget about scanf().

--
------------------- Richard Callwood III --------------------
~ U.S. Virgin Islands ~ USDA zone 11 ~ 18.3N, 64.9W ~
~ eastern Massachusetts ~ USDA zone 6 (1992-95) ~
--------------- http://cac.uvi.edu/staff/rc3/ ---------------
Nov 13 '05 #7
In article <9d************************@posting.google.com>, Rob
wrote:
My program isn't handling invalid input correctly. If the user
enters "1abc", then it treats that as if they had just entered
the number 1, which is incorrect. If they enter valid input of
1, 2 or 3, then it works. If they enter a string such as "abc"
as input, then I get an infinite loop where my menu is printed
over and over. I'm not sure how to fix this. Here's my code so
far. Thanks for any help.


You need to:
* Ensure that your prompt gets printed/flushed before scanf is
called.
* Pay attention to the return value of scanf.
* Ignore trailing characters up to the next newline.
* Handle error conditions and EOF.

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int option;
int n;
while (1) {
printf("Choose an option [1-3]: ");
fflush(stdout);
n = scanf("%d%*[^\n]", &option);
if (n == 1) {
if (option < 0 || option > 3) {
printf("Invalid option. Please try again.\n");
} else {
puts("OK\n");
break;
}
} else if (n == EOF) {
printf("Unexpected end of input. Terminating.\n");
return EXIT_FAILURE;
} else {
printf("Invalid option. Try again.\n");
clearerr(stdin);
scanf("%*[^\n]");
}
}
/* Do something with option */
return 0;
}
--
Neil Cerutti
Nov 13 '05 #8

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

Similar topics

4
by: Tweaxor | last post by:
Hey, forgive me of my ignorance! Can someone tell me why this won't work. I have this coded but it won't compile is this not permitted in C. kg = kilograms and d = distance // this is not...
13
by: na1paj | last post by:
here's a simple linked list program. the DeleteNode function is producing an infinit loop i think, but i can't figure out where.. #include <stdio.h> typedef struct { char *str; //str is a...
4
by: Jeffrey Barrett | last post by:
Can someone tell me why I'm having this problem: When I select drink 5 and deposit too little money, there's a problem with the 'difference' variable. Try to deposit $.80 instead of the full $.85...
15
by: honeygrl33 | last post by:
i accidentially erased something someone helped me write and i am soooo in trouble if i dont fix this, i really need the help!!!!! heres what i have: /* */ #include <stdio.h> #include...
8
by: drose0927 | last post by:
Please help! I can't get my program to exit if the user hits the Escape button: When I tried exit(EXIT_SUCCESS), it wouldn't compile and gave me this error: Parse Error, expecting `'}''...
59
by: rami | last post by:
please everybody ,can anyone tell me how to do an infinite loop in C
4
by: ghostrider | last post by:
The program that I wrote below only sees the first set of functions. I was wondering how do I go about adding loops to make it work, with any numbers that I put it it. Can You help me with this? ...
33
by: dmoran21 | last post by:
Hi all, I am a mathematician and I'm trying to write a program to try out a formula that I've derived. However, it seems that I've got an infinite loop and I don't quite understand why. I was...
5
by: shanti | last post by:
hai, i have developed a c-code to push integers into a stack (an array). in the program there are three inputs which has to be given through keyboard. the inputs are "choice", "option","S_R_NO"...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
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
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
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.