c++: getchar() doesn't work on conditional control statement

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • windscar
    New Member
    • Feb 2010
    • 2

    c++: getchar() doesn't work on conditional control statement

    Hello Everybody!

    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.

    Here the code:
    Code:
    #include <ncurses.h>
    #include <iostream>
    	using namespace std;
    #include <stdlib.h>
    
    void menu();
    
    int main() {
    	int stop(0);
    	int choice;
    	
    	while (stop == 0) {
    		menu();
    		cout << "Input: ";
    		cin >> choice;
    		switch (choice) {
    			case 1  : cout << "press any key ...";
    				      getchar();
    				      cout << endl << endl;
    				      break;
    			case 2  : stop = 1;
    				      break;
    			default : cout << "Prompt Error..." << endl << endl;
    				      break;
    		}
    	}
    	return 0;
    }
    
    void menu () {
    	cout << "Menu: \n";
    	cout << "1. Keep looping" << endl;
    	cout << "2. Stop and quit" << endl;
    }
    Can somebody help me and explain why getchar() doesn't work?

    Thank you,
    Wind Scar
  • windscar
    New Member
    • Feb 2010
    • 2

    #2
    Hello everybody,

    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:
    Code:
    #include <ncurses.h>
    #include <iostream>
    	using namespace std;
    #include <stdlib.h>
    
    void menu();
    
    int main() {
    	int stop(0);
    	int choice;
    	
    	while (stop == 0) {
    		menu();
    		cout << "Input: ";
    		cin >> choice;
    		switch (choice) {
    			case 1  : cout << "press ENTER ...";
    				  getchar();
    				  cin.get();
    				  cout << endl << endl;
    				  break;
    			case 2  : stop = 1;
    				  break;
    			default : cout << "Prompt Error..." << endl << endl;
    				  break;
    		}
    	}
    	return 0;
    }
    
    void menu () {
    	cout << "Menu: \n";
    	cout << "1. Keep looping" << endl;
    	cout << "2. Stop and quit" << endl;
    }
    It does work! Anyway, if you other better solutions, I'll appreciate it if you share it :)

    Comment

    Working...