【问题标题】:getline() skips after multiple callsgetline() 在多次调用后跳过
【发布时间】:2015-01-02 06:25:02
【问题描述】:

在阅读了很多关于 getline 被跳过的线程后,我仍然无法让我的程序运行。

首先我阅读了用户的输入。它应该类似于“ADD 1”。然后我显示“添加”之后的值。我再次开始阅读用户的输入,并且由于某些原因,下面的 getline 只是不想从“ss”中读取,并将命令留空。

代码如下:

string lecture, command;
getline(cin, lecture);
stringstream ss(lecture);
getline(ss, command, ' ');
while(command.compare("EXIT") != 0) {
    if(command.compare("ADD") == 0) {
        string id;
        getline(ss, id);
        cout << id << endl;
    }
    lecture = "";
    command = "";
    getline(cin, lecture);
    ss.str(lecture);
    getline(ss, command, ' ');
}

和输入/输出(输出用“>”区分):

ADD 1
>1
ADD 2
(From here -> Goes back to getline(cin, lecture))

我不明白我做错了什么? 循环外的第一个 getline 运行良好,但随后就出错了。 很明显,命令保持为空,即使在 getline 之后也是如此。但是当我在 getline(ss, command, ' ') 行时,我看不出为什么会有任何尾随的 '\n',因为 getline 丢弃了 '\n',因此 command 应该具有新值。

谢谢!

编辑: 有人评论说 stringstream.str 没有正确重置或其他什么,他是对的(你为什么删除你的答案?!)!我知道在每个循环中重新创建对象 stringstream 并且它可以工作。如果有比重新创建对象更好的解决方案,我会让线程保持打开状态。

现在 ss 基本上是一个指针,在循环的每次迭代中我都会这样做:ss = new stringstream(lecture)

【问题讨论】:

  • 我看过这个thread,我应该不会遇到和我没有在我的程序中使用任何 cin >> 相同的问题,对吧?
  • 有人评论说 stringstream.str 没有正确重置或其他什么,他是对的(你为什么删除你的答案?!)!我知道在每个循环中重新创建对象 stringstream 并且它可以工作。如果有比重新创建对象更好的解决方案,我会让线程保持打开状态。
  • ss.clear() 应该重置字符串流上的任何错误。没有理由一直更新它。如果您需要清除任何剩余数据,ss.str(""); 会这样做。
  • 我混合了@RetiredNinja 和 RobinHsu 的答案,它只使用 getline 并将 "\n" 添加到字符串流中,并使用 ss.clear() !谢谢大家。

标签: c++ whitespace cin getline stringstream


【解决方案1】:

我认为您的 ss 不包含 endl 并且很困惑。另一件奇怪的事是指令ss.str(lecture); 对我的机器没有影响。这可能是图书馆的错误??无论如何,我在ss 上使用&gt;&gt; 而不是getline,因为ss 可以流入/流出:

string lecture, command;
getline(cin, lecture);
stringstream ss;
ss << lecture << endl;
ss >> command;

while(command.compare("EXIT") != 0) {
    if(command.compare("ADD") == 0) {
        string id;
        ss >> id;
        cout << id << endl;
    }
    lecture = "";
    command = "";
    getline(cin, lecture);
    ss << lecture << endl;
    ss >> command;
}

或者,要使用getline(),我也让它工作,但输入“EXIT”不会退出,您需要输入“EXIT”,即“EXIT”后有一个空格,因为它正在寻找每次命令后的空格。 (您的程序中的一个错误)。不管怎样,这是getline() 版本:

string lecture, command;
getline(cin, lecture);
stringstream ss(lecture + "\n");
getline(ss, command, ' ');

while(command.compare("EXIT") != 0) {
    if(command.compare("ADD") == 0) {
        string id;
        getline(ss, id);
        cout << id << endl;
    }
    lecture = "";
    command = "";
    getline(cin, lecture);
    ss.str(lecture + "\n");
    getline(ss, command, ' ');
}

【讨论】:

  • 其实ss是没有必要的。 cin 本身就是一个流。因此,只需使用 cin &gt;&gt; commandcin &gt;&gt; id 代替 ss 所做的,这是我的第一个解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-04
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 2012-08-24
  • 1970-01-01
  • 2019-07-09
相关资源
最近更新 更多