cin << 名称 << endl; cout >> "我的名字是" << name << endl;
问问题
41 次
1 回答
0
问题
当你说cin >> smth
,你想得到精确的东西,仅此而已。结束行标记不是其中的一部分,因此不会被消耗。除非你有一个特殊的 line 类型,但标准库中没有这样的东西。
当你使用getline
你说你想得到一条线。一条线是以 结尾的字符串,\n
结尾是它的组成部分。
所以问题是在缓冲区中std::cin
留下了一个结束行字符。\n
例子
std::cin >> smth;
+---+---+---+---+---+----+
|'H'|'e'|'l'|'l'|'o'|'\n'| // In smth will be "Hello"
+---+---+---+---+---+----+
+----+
|'\n'| // But new-line character stays in buffer
+----+
std::cin >> smth2; // Its same like you would press just an 'enter', so smth2 is empty
解决方案
- 利用
std::cin.getline
或者
- 使用
std::cin >> smth;
+std::cin.ignore();
于 2017-08-15T20:55:52.340 回答