I am a beginner that try to learn C++ programming. I work in Linux Ubuntu Karmic Koala (9.10) environment.
I got a problem with getchar(). The function works well in a simple program. But when I use it in while (cond.) and switch (var.) , the function doesn't work, it doesn't even ask me to input character (including "\n"). Or maybe there are other reasons why getchar() doesn't work.
I am sorry if I repost the same question. But I already searched on Internet but I still can't find the answer. So I decided to ask this problem to this forum.
getch() is non-standard and _getch() is even less so. Avoid using conio.h as far as possible.
Let me explain why your getchar() isn't working. That is because you use cin at line 15. When you input a number a newline along with the number will also be read. So, the getchar() reads the newline and hence your program never pauses.
Precede your getchar() call by a fflush() call to flush out unwanted newlines or any other char. Like this: fflush(stdin);
That is all, and your getchar() will then work as you expect it to. However, you may want to change the "Pressy any key" to "Press ENTER".
@ Dear olredixsis,
I work on Linux Ubuntu Karmic Koala (9.10), so _getch() won't be recognized by its compiler (g++) because Linux doesn't have conio.h. I already mentioned it, didn't I? Anyway, thank you for trying to help me :)
@ Dear unoriginal,
Thank you for your explanation. But it still doesn't work as I expect it. I add fflush(stdin) like you said, and my code becomes like this:
@ Dear Computergeek01,
Thank you for trying to help me. I already tried your advice. But it still doesn't work. I put fflush(stdin) on line 16 (below cin >> choice). My code becomes like this:
Finally with some experiments, I can make the getchar() works as my expectation. By putting getchar() and cin.get() together. So, my code becomes like this: