[英]c++ getline does not seem to recognize newlines in input piped to stdin
[英]getLine() does't seem to work after first input - C++
我目前是 C++ 新手,正在学习基本语法。
我正在探索 getLine() 的工作原理,并尝试比较标准输入和 getline()。
#include <iostream>
#include <string>
using namespace std;
int main(){
string name1;
string name2;
cout << "Type your name please: ";
cin >> name1;
cout << "Your name is: " << name1 << endl;
cout << endl;
cout << "Type your name again please: ";
cin.ignore();
getline(cin, name2);
cout << "Your name is: " << name2 << endl;
return 0;
}
预期输出:
Type your name please: John Doe
Your name is: John
Type your name again please: John Doe
Your name is: John Doe
电流输出:
Type your name please: John Doe
Your name is: John
Type your name again please: Your name is: Doe
导致这种情况的问题可能是什么? 任何帮助将不胜感激。
您应该清除输入流并且不仅忽略一个字符,而且忽略流中的所有字符:
#include <iostream>
#include <limits>
#include <string>
int main() {
std::string name1;
std::string name2;
std::cout << "Type your name please: ";
std::cin >> name1;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Your name is: " << name1 << std::endl;
std::cout << std::endl;
std::cout << "Type your name again please: ";
std::getline(std::cin, name2);
std::cout << "Your name is: " << name2 << std::endl;
return 0;
}
如您所见cin >> name1;
最多只能读取第一个空格。 输入缓冲区中剩余的是Doe\n
。 (注意第一个字符是空格)。
现在cin.ignore();
将忽略 1 个字符(在这种情况下为空格)。 输入缓冲区现在包含Doe\n
。 有关更多详细信息,请参见此处: https ://en.cppreference.com/w/cpp/io/basic_istream/ignore
下一个getline(cin, name2);
将读取所有数据到下一个新行。 那是Doe
,您将获得它作为第二个输出。
我认为您想丢弃完整的输入,而不仅仅是一个字符。 这应该这样做:
cin.ignore(std::numeric_limits<std::streamsize>::max());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.