我试图从下面程序的标准输入中读取第n行.但是,控制台在输入任何number...not之前都会打印出“当前行是”,以确定出了什么问题。谢谢你帮忙。
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;
}发布于 2013-12-04 00:54:49
当下一个字符无法满足格式时,使用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跳过前导空格。如前所述,您还应该在处理输入之前验证输入是否确实成功。
发布于 2013-12-04 02:22:21
为了获得n,您必须输入一个数字并按下Enter按钮。正如@Kuhl所言,一旦the operator>>的格式不能满足下一个字符的要求,它就会停止。
这意味着getline(cin, currentline)第一次运行时将得到'\n'!然后,程序将输出“当前行是\n”,而'\n‘将不会显示在控制台上。
如果您想得到n和“currentline”,您可以选择@Kuhl的答案,或者编写如下程序:
getline(cin, currentline);
while(n>0) {
// anything you want
}getline(cin, currentline)将帮助您跳过'\n'后面的数字'n‘。
https://stackoverflow.com/questions/20364677
复制相似问题