Question:
C program Question regarding do while loops?
2fishBLUEfish
2009-02-26 18:40:44 UTC
I've been working on a program and i'm having a problem with my loop.
here's an example:
#include
main()
{
char ch;
do{
printf("blah\n");
ch=getchar();

} while(ch =='a');

getchar();

return 0;
}

basically i want to do the stuff in the loop while ch== 'a' or ch=='A', but when i run the program it terminates after two loops...so how can i fix it to only terminate when ch is assigned a value other than 'a' or 'A'
Six answers:
Ambients
2009-02-26 19:55:16 UTC
Question is on C, not C++. So no cin! The other solutions are buggy or don't do the trick. My solution is:



char ch;



do

{

printf("\nResponse: ");

//scanf("%c",&ch);

ch = (char)getchar(); //Comment that line and try scanf instead



fflush(stdin); //to discard unwritten data



//Lastly, a fix for your do...while

}while(!(ch=='a' || ch=='A'));
Pat M
2009-02-26 19:08:57 UTC
The reason it is terminating after 2 loops is because you are using getc(). When I type "a" in on the command line and press enter, the input stream the compiler actually sees is "a\n". This is why it is only going through the loop twice, it reads the a, continues with the loop, then reads the '\n' (which is the next char in the input buffer) which is not equal to 'a'. In fact, if you type "aaaa" you will see it gets around the loop 5 times.



Oh and Syntax, C++ was designed as a superset of C. Anything that will compile and run in C will also compile and run in C++.
tbshmkr
2009-02-26 19:24:42 UTC
Move getchar() into the do-while loop

==

#include



int main()

{

char ch;

do{

printf("blah\n");

ch=getchar();



getchar();



}while (ch == 'a' || ch == 'A' );



return 0;

}
anonymous
2009-02-26 18:49:53 UTC
this worked for me!!!!!!!





#include

#include

#include

using namespace std;

int main()

{

char ch = ' ';



do

{

printf("blah\n");

cin>>ch;

}while(ch =='a'|| ch=='A');

return 0;

}



scratch that due to my inexperience in C programming...lol ill stick to C++ language i was taught in...lol



but.....tbshmkr is right it worked once getchar(); was put into the loop, he deserves best answer not these other haters





see they gave him thumbs down even though he gave you the perfect reason for it not working.
anonymous
2016-10-26 05:22:30 UTC
on the same time as(!(PINA & (a million<
mdigitale
2009-02-26 18:46:05 UTC
The way you have written it, it will terminate if you enter any character other than 'a' (sans quotes)


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...