![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Apr 2005
Posts: 5
Rep Power: 0
![]() |
Do-While loop runs only twice
I'm fairly new at programming and need some help whit this program. The DO-while loop only prompts to Run Again only once and just quites after running.
code: #include<stdin.h> main() { int x,y,z; char ans; do { ... printf("Run Again?(y,n)"); scanf("%c",&ans); } while(ans==89 || ans==121); } Please help |
|
|
|
|
|
#2 |
|
Newbie
Join Date: Apr 2005
Posts: 22
Rep Power: 0
![]() |
the problem is that scanf("%c",ans); reads only one character the '\n'(new line character) that is inserted by the enter button is read burring the second run and gets out of the loop as the while condition is 0.
to solve this add getchar() at the end of the loop. so the code will be looking like this #include<stdio.h>
main()
{
int x,y,z;
char ans;
do
{
printf("Run Again?(y,n)");
scanf("%c",&ans);
getchar();
}
while(ans==89 || ans==121);
}Actually if the user enters a lot of charactrs this will take only the first one. If you want to "clean" more chars you have to declare an array of chars and use gets(char *) like this: #include<stdio.h>
main()
{
int x,y,z;
char ans, useless[80];
do
{
printf("Run Again?(y,n)");
scanf("%c",&ans);
gets(useless);
}
while(ans==89 || ans==121);
}finally the same effect will have the command "fflush(stdin);" after the fscan in the loop. This cleans everything that has been typed by the user and hasn't yet been "read" by the program Last edited by Daniel_kd; Apr 3rd, 2005 at 7:47 PM. |
|
|
|
|
|
#3 |
|
I eat cake for breakfast.
![]() ![]() ![]() ![]() Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9
![]() |
I suggest using the fflush(stdin); statement instead of getchar - getchar might screw up on a different system.
|
|
|
|
|
|
#4 |
|
Newbie
Join Date: Apr 2005
Posts: 5
Rep Power: 0
![]() |
thanks alot daniel and ooble. I was looking for the fflush function but i could remeber it until i saw it here. anyway, the fflush fuction didnt work for some reason, it said stdin was undefined. I don;t know whats going on. The getchar function worked so thanks alot for all you help.
|
|
|
|
|
|
#5 |
|
Newbie
Join Date: Jan 2005
Posts: 20
Rep Power: 0
![]() |
Just a small note:
1. Do not use the fflush function on input buffers, this is undefined behaviour. 2. Never use the gets function, use the fgets function instead. To flush the input buffer, you can use the getchar function in a while loop: while ((ch = getchar()) != '\n' && ch != EOF); |
|
|
|
|
|
#6 | |
|
Newbie
Join Date: Apr 2005
Posts: 1
Rep Power: 0
![]() |
Quote:
#include<stdio.h> #include<conio.h> main() { int x,y,z; char ans; do { ... printf("Run Again?(y,n)"); ch = getche(); } while(ch != 'n' || ch!= 'N"); } |
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|