【问题标题】:C++ getline not able to take inputC ++ getline无法接受输入
【发布时间】:2015-02-02 03:58:26
【问题描述】:

我想读一个句子来解读,但是出了点问题。当我不输入任何字符时,它会打印出“The sentence is”和“Decoded sentence is”,但是当我输入一个或多个字符时,它只会坐在那里什么都不做。我不认为这可能是 MySentence 类的错误,因为它甚至不打印“The sentence is”。

#include <iostream>
#include <stdio.h>
#include "MySentence.h"
#include "Corpus.h"
#include <string>
using namespace std;

int main() {
    Corpus corp;
    std::cout << "The proportions are: ";
    for(int i = 0; i<26; i++) {
            cout << corp.proportion(i+97) <<", ";
    }
    cout << endl;
    cout << "Enter sentence terminated by <ENTER> ";

    string s= "";
    getline(cin, s);
    cout << "The sentence is " << s;
    MySentence sent(s);
    sent.decode(corp);
    cout << endl << "Deoded sentence is: " << sent.sentence;
    return 0;
}

【问题讨论】:

  • 您在输入字符后是否按回车键?
  • 是的,它只是换了一个新行。
  • 试试这个:cout &lt;&lt; "The sentence is " &lt;&lt; s &lt;&lt; endl;
  • 作为@n.m。意思是说,它有助于在执行可能挂起的语句之前刷新输出。

标签: c++


【解决方案1】:

按照 n.m. 的建议。尝试在行尾添加 endl

cout

因为缓冲区可能没有被刷新并且问题出在 MySentence 类中。

可能有帮助的有趣帖子是 Buffer flushing: "\n" vs. std::endl

【讨论】:

  • 好吧,有点效果。它打印“句子是”加上我输入的任何内容,但停在那里。它永远不会到达“解码的句子......”
  • 您是否尝试过使用调试器(例如 gdb)来单步调试代码并查看其挂起的位置?
猜你喜欢
  • 2016-01-24
  • 2016-01-24
  • 1970-01-01
  • 1970-01-01
  • 2015-04-13
  • 1970-01-01
  • 1970-01-01
  • 2017-01-31
  • 1970-01-01
相关资源
最近更新 更多