我正在尝试从以下程序的标准输入中读取第 n 行。但是,在我输入任何数字之前,控制台会打印出“当前行是”……不知道出了什么问题。感谢您的帮助。
int main()
{
string currentLine;
int n;
cin >> n;
cout << n << endl;
while (n > 0)
{
getline(cin, currentLine);
cout << "current line is" << currentLine << endl;
n--;
}
return 0;
}
最佳答案
使用 operator>>()
的格式化输入会在下一个字符无法满足其格式时立即停止。对于整数,当没有进一步的数字时它会停止,例如,当下一个字符是一个空格时,比如进入该行的换行符。
std::getline()
读取直到找到第一个换行符。读取整数时,前左右一。您可能想要提取此换行符和可能的其他空格。例如,您可以使用
if (std::getline(std::cin >> std::ws, currentLine)) {
// do something with the current line
}
else {
// deal with a failure to read another line
}
操纵器 std::ws
跳过前导空格。如上所述,您还应该在处理输入之前验证输入是否确实成功。
关于c++ - getline 不等待输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20364677/