std::getline 在 for 循环中不起作用

新手上路,请多包涵

我试图在一个字符串变量中收集用户的输入,该变量在指定的时间内接受空格。

由于通常的 cin >> str 不接受空格,所以我会使用 std::getline from

这是我的代码:

 #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
    int n;
    cin >> n;
    for(int i = 0; i < n; i++)
    {
        string local;
        getline(cin, local); // This simply does not work. Just skipped without a reason.
        //............................
    }

    //............................
    return 0;
}

任何想法?

原文由 Yana D. Nugraha 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 740
2 个回答

如果您输出存储在 local (顺便说一句,这是一个糟糕的变量名:P)中的内容,您可以看到为什么这会失败:

 #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
    int n;
    cin >> n;
    for(int i = 0; i < n; i++)
    {
        string local;
        getline(cin, local);
        std::cout << "> " << local << std::endl;
    }

    //............................
    return 0;
}

输入您的号码后,您将看到它在 > 之后立即打印一个换行符。然后它继续输入其余部分。

这是因为 getline 给了你输入号码后剩下的空行。 (它读取数字,但显然没有删除 \n ,所以你留下了一个空行。)你需要首先摆脱任何剩余的空白:

 #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
    int n;
    cin >> n;
    cin >> ws; // stream out any whitespace
    for(int i = 0; i < n; i++)
    {
        string local;
        getline(cin, local);
        std::cout << "> " << local << std::endl;
    }

    //............................
    return 0;
}

这按预期工作。

题外话,也许它只是为了手头的片段,但如果你没有 using namespace std; ,代码往往 更具 可读性。它违背了命名空间的目的。不过,我怀疑这只是为了在这里发帖。

原文由 GManNickG 发布,翻译遵循 CC BY-SA 2.5 许可协议

我的猜测是你没有正确阅读 n ,所以它转换为零。由于 0 不小于 0,因此循环永远不会执行。

我会添加一些仪器:

 int n;
cin >> n;
std::cerr << "n was read as: " << n << "\n"; // <- added instrumentation
for // ...

原文由 Jerry Coffin 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题