Switch in a loop

Hi.
I have the following problem: if i use the "switch" in a loop like "do-while" i cannot see any output until i have exited the loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
int main(){
    char ch;
    do{
        ch=getch();
        switch(ch){
		case 'A': cout<<"A\n"; break;
		case 'B': cout<<"B\n"; break;
		case 'C': cout<<"C\n"; break;
                case 'D': cout<<"D\n"; break;
        };
    }while(ch!='e');
    return 0;
}


Example of running this program:
Type A. Nothing on the screen.
Type B. Nothing on the screen.
Type C. Nothing on the screen.
Type e. Everything appears: A,B,C.

In another program, with a simple "switch", no loop, everything is ok.
I am using Visual C++ 6.0.

LE: I just ran this program in CodeBlocks and it works fine.. Anyway can someone tell me what could be the problem in VC++?
Last edited on
getch() is a function from the deprecated library <conio.h> Therefore, the function might not behave the way you expect among different compilers.

Try putting in a default case in your switch to show what ASCII number/letter the ch recieves.
Maybe the characters are buffered.
Try adding cout.flush() right after the switch.
@Daleth The default didn't work..

@toum It works. Thanks a lot. If it's ok, can you please explain to me a bit more? I don't understand what was happening.
Last edited on
In order to display something in the console, system calls are performed. Making these calls has a non-negligible computational cost, independently of the computation of what is displayed.
One common strategy to reduce that cost is to accumulate successive display command in a memory buffer and process them all at once, thus reducing multiple calls to only one.

What I think happened in your case is that the system thought it should keep accumulating and therefore did not display the text.
The flush() command ordered the system to display what was stored into the buffer.
I got it.
I really appreciate your help. Again, thank you very much.
Topic archived. No new replies allowed.