getline没有等待输入

时间:2013-12-04 00:45:07

标签: c++

我正在尝试从以下程序中的标准输入读取第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;
}

2 个答案:

答案 0 :(得分:3)

使用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跳过前导空格。如上所述,您还应该在处理输入之前验证输入是否实际成功。

答案 1 :(得分:2)

要获得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'。

相关问题