I have a small, simple program with menu and submenus. User choose from 1-9 and hits enter. I want the code to read ONLY numbers 1-9 removing " " from stdin. I've tried sth like this:
#include <cstdio>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
class cProgram
{
private:
char W;
public:
char choice(void);
void choice(int _W);
void showSubeMenu1(void);
void showSubeMenu2(void);
void showMainMenu(void);
};
char cProgram::choice()
{ return W; };
void cProgram::choice(int _W)
{ W = _W; };
void cProgram::showMainMenu(void)
{
cout << "MAIN MENU:" << endl
<< "[1] option 1" << endl
<< "[2] option 2" << endl
<< "<0> quit" << endl
<< "Your choice: ";
choice(cin.get());
getchar();
}
switch (choice())
{
case '1': choice('n'); showSubeMenu1(); break;
case '2': choice('n'); showSubeMenu2(); break;
case '0': break; // EXITS the program
default: choice('n'); showMainMenu(); break;
}
// choice('n'); sets W to neutral char (not 1,2 or 0)
Everything works fine, until the user hits " " instead of normal key. By "normal" i mean not " ". So, when the user hits enter, it is a must to hit enter again (twice in a row). Other way the program behaves weird.
See Question&Answers more detail:os