问题
I'm Writing a program for Billing System. I'm using do-while loop in my program. And the program is executed according to user input. If the user want to continue the execution, the program will be continue. But I Got a prob in Execution. I was trying my logic in simple do-while loop. The same Problem arises for simple do-while loop also.
Problem is: If the input is yes, the program does not get the further input from user.
That simple do-while loop is:
#include <stdio.h>
main()
{
int c;
char ch;
do
{
printf("enter the no less then 4:");
scanf("%d",&c);
switch(c)
{
case 1:
printf("In 1\n");
break;
case 2:
printf("In 2\n");
break;
case 3:
printf("In 3\n");
break;
}
printf("do u want to continue?:");
ch=getchar();
}while(ch=='y');
}
If i put while(ch != 'n')
instead of while(ch=='y')
the program working fine. I couldn't understand the problem behind this. Please Help me to rectify this. And Explain about this problem.Thank u in advance.
回答1:
first run, 3 is printed, user types "y" and presses return
getchar() reads 'y' and program loops
second time, getchar() reads newline character from the previous key press
newline is not 'y' so program does not loop
回答2:
Several problems:
- getchar returns an int, not a char, so
ch
must be anint
just like c. - scanf needs a pointer to go with the %d, so it should be
scanf("%d", &c);
- The
while
should rather test for EOF, as inwhile ((ch = getchar()) != EOF)
- Note that the input will contain the newlines, which you should deal with (e.g. ignore).
This should be quite robust:
#include <stdio.h>
int main(void)
{
int c, ch;
for (;;) {
printf ("Enter a number (1, 2 or 3):");
fflush (stdout);
if (scanf ("%d", &c) == 1) {
switch (c) {
case 1:
printf ("In 1\n");
break;
case 2:
printf ("In 2\n");
break;
case 3:
printf ("In 3\n");
break;
}
printf ("Do you want to continue? [y/n]:");
fflush (stdout);
while ((ch = getchar ())) {
if (ch == 'y')
break;
else if (ch == 'n' || ch == EOF)
return 0;
}
} else {
printf ("That was not a number. Exiting.\n");
return 0;
}
}
}
回答3:
While(ch=='y') or the character whatever in while() it will sent to case 3 as per your coding....y is pressing ,it wil sent to case 3 otherwise it wont work
回答4:
Instead of reading the answer using getchar
, use fgets
.
As others explained, the second getchar
call gives you the newline, which was typed after the first y
.
With fgets
, you'll get everything the user typed. Then you can check if it's y
(just check the first character, or use strcmp
).
来源:https://stackoverflow.com/questions/14377793/reading-user-command-to-continue-does-not-work