Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

c++ - cin.get() and omitting newline char

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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::cout and std::cin for input and output. They are stream from library <iostream>. You can also write using namespace std; and then you needn't write std::. Function printf() 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 ( ' ', ' ', ' ' ). If you would like read number and ignore white spaces ( in default they are used like separators ) then you can use this code:

int x;
cin >> x;
if ( cin.fail() ) cout << "Reading error. It is not a number." << endl;
// cin.eof() means end of file, in this case it is end of input stream

I know when you want read something then user have to write requested data and ' '. Character ' ' 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...