help with infinite loops and scanf

R

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 */
}
}
 
A

ak

On 26 Jul 2003 13:03:17 -0700, (e-mail address removed) (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
 
B

Burne C

Rob said:
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.
 
A

amanayin

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");
}
 
E

Emmanuel Delahaye

Burne C said:
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.
 
A

ak

|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
 
C

Cousin Ricky

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 said:
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().
 
N

Neil Cerutti

Rob said:
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;
}
 
P

Peter Shaggy Haywood

Groovy hepcat Rob was jivin' on 26 Jul 2003 13:03:17 -0700 in
comp.lang.c.
help with infinite loops and scanf's a cool scene! Dig it!
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.

Break the problem down. Divide and conquer. Here are some tips on
how to do that.
First, write a function that reads in a number. Call it getnum() or
something like that. Have it take a string to display as a prompt.
Display this prompt. Then use fgets() to read in a line of input, and
sscanf() or strtol() to scan for a number, checking that proper
numerical input has been entered. If not, then output an error
message, re-display the prompt and try again. If fgets() fails, maybe
you need a way to quit the function and return an error flag. (To
return a number and an error flag, one of these will need to be passed
back via a pointer.) Otherwise, when done, return the number to the
calling function. Also, when using fgets(), remember to check whether
a whole line was read, and take appropriate action if not (ie., read
in and discard the rest of the line).
Next, where your program needs to ask the user to enter a number,
call your getnum() function in a loop, passing an appropriate string
for the prompt. If it returns an error flag, take appropriate steps.
Otherwise, check whether the number you get back is within range, and
keep looping if not, otherwise quit looping.
And then you have your number.
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,

You can do this with strtol() or sscanf().
Using strtol(), check the endp argument to determine whether there
was any extra (non-numerical) input.
Using sscanf(), use an extra "dummy" conversion specifier (for char)
and argument and check the return value to determine whether the input
contains any non-numeric data. Remember, the return value of sscanf()
indicates the number of items assigned; and in this case you want a
return value of 1. (A return value of 2 means that there are extra
characters after the number, while a return value of 0 means that
there was no number.) So doing the following (after first removing any
newline character from the end of the string) should do what you want:

char dummy;
int num;
int chk;
....
chk = sscanf(input_string, "%d%d", &num, &dummy);
if(1 != chk)
{
/* invalid (non-numerical) input */
}
else
{
/* numerical input */
}
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.

Read the FAQ: http://www.eskimo.com/~scs/C-faq/top.html

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,140
Latest member
SweetcalmCBDreview
Top