cin.get()和省略换行符 [英] cin.get() and omitting newline char
问题描述
我有一个小,简单的程序与菜单和子菜单。用户从1-9中选择并点击进入。我想代码读取只有数字1-9删除\\\
从stdin。我已经尝试sth这样:
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)
一切正常,直到用户命中\\\
而不是普通键。 正常我的意思不是\\\
。所以,当用户点击enter,它是一个必须再次输入(连续两次)。
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.
推荐答案
我不知道你的问题,但我有几个技巧。当你使用C ++时,你应该使用 std :: cout
和 std :: cin
来输入和输出。它们是从库< iostream>
的流。你也可以使用命名空间std; 编写,然后你不需要写
std ::
。函数 printf()
来自C,并且类型不安全,因此您不应在C ++中使用它。
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.
方法 cin.get
只读取1个字符,也可以是白色字符('\\\
','\t','')。如果你想读取数字并忽略空格(默认情况下它们像分隔符),那么你可以使用这个代码:
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:
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
$ b b
我知道当你想要读取东西,然后用户必须写入请求的数据和'\\\
'。字符\\\
很重要。我从来没有尝试过,但我认为它可以重新定义。我在某处阅读。
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.
我希望我的提示有用
这篇关于cin.get()和省略换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!