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 “\n” 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 “\n” instead of normal key. By “normal” i mean not “\n”. So, when the user hits enter, it is a must to hit enter again (twice in a row). Other way the program behaves weird.
I am not sure about your problem but I have a few tips for you. When you are using C++ then you should use
std::coutandstd::cinfor input and output. They are stream from library<iostream>. You can also writeusing namespace std;and then you needn’t writestd::. Functionprintf()comes from C and is type unsafe so you shouldn’t use it in C++.Also streams offer many functions for getting information about successful or unsuccessful reading/writing etc. I really recommend it to you.
Method
cin.get()reads only 1 character and it also can be a white character ( ‘\n’, ‘\t’, ‘ ‘ ). If you would like read number and ignore white spaces ( in default they are used like separators ) then you can use this code:I know when you want read something then user have to write requested data and ‘\n’. Character ‘\n’ is important. I have never tried it but I think that it can be redefined. I read it somewhere.
I hope that my tips are helpful