【问题标题】:Why is cout printing twice when I use getline?为什么当我使用 getline 时 cout 打印两次?
【发布时间】:2012-08-10 01:19:01
【问题描述】:

我正在尝试使用 getline 读取一串文本。出于某种原因,它会打印两次“请输入您的选择”:

Please enter your selection
Please enter your selection

如果我键入无效文本,它会再次循环,之后每次循环只打印一次。

while (valid == false) {    
    cout << "Please enter your selection" << endl;
    getline (cin,selection);

    // I have a function here which checks if the string is valid and sets it to true 
    // if it is valid.  This function works fine, so I have not included it here.  The while
    // look breaks correctly if the user enters valid input.
}

有人知道为什么会发生这种情况吗?

谢谢

【问题讨论】:

  • 在第一次打印后尝试刷新 std::cout:flush(cout);
  • @Ben, endl 应该为交互式设备自动执行此操作。
  • 你能给我们一些(简短的)可编译代码来重现问题吗?
  • 您可以在循环之前尝试cin.ignore(INT_MAX); cin.clear(); 吗?
  • @scientiaesthete,这不会一直读到 EOF 吗?这是我的理解,虽然我可能错了。

标签: c++


【解决方案1】:

可能当您进入循环时,输入缓冲区中仍有来自先前操作的内容。

getline捡到,发现无效,然后循环再次运行。


举例来说,假设在您进入循环之前,您读取了一个字符。但是,在熟模式下,您需要输入字符 一个换行符才能执行操作。

所以,你读取了这个字符,换行符就留在了输入缓冲区中。

然后您的循环开始,读取换行符,并认为它无效,然后循环返回以获取您的 实际 输入行。

这是一种可能性,当然,也可能有其他可能性 - 这在很大程度上取决于循环之前的代码以及它对cin的作用。

如果 的情况,类似于:

cin.ignore(INT_MAX, '\n');

在循环可能修复它之前。

或者,您可能希望确保在任何地方都使用基于行的输入。


这里有一些代码可以查看该场景的实际效果:

#include <iostream>
#include <climits>

int main(void) {
    char c;
    std::string s;

    std::cout << "Prompt 1: ";
    std::cin.get (c);
    std::cout << "char [" << c << "]\n";
    // std::cin.ignore (INT_MAX, '\n')

    std::cout << "Prompt 2: ";
    getline (std::cin, s);
    std::cout << "str1 [" << s << "]\n";

    std::cout << "Prompt 3: ";
    getline (std::cin, s);
    std::cout << "str2 [" << s << "]\n";

    return 0;
}

连同成绩单:

Prompt 1: Hello
char [H]
Prompt 2: str1 [ello]
Prompt 3: from Pax
str2 [from Pax]

您可以在其中看到它实际上并没有等待提示 2 的新输入,它只是获取您在提示 1 输入的行的其余部分,因为字符 e、l、lo\n 仍在输入缓冲区中。

当您取消注释 ignore 行时,它会以您期望的方式运行:

Prompt 1: Hello
char [H]
Prompt 2: from Pax
str1 [from Pax]
Prompt 3: Goodbye
str2 [Goodbye]

【讨论】:

  • cin.ignore(INT_MAX, '\n');已修复它。非常感谢:)也感谢您的详细回复。
【解决方案2】:

我会使用调试器(例如 linux 中的 gdb)来检查原因。既然可以找到真正的答案,为什么还要提出理论?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-03
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多