C ++ getline无法获取输入

时间:2015-02-02 03:58:27

标签: c++

我试图用一句话来解读,但是出了问题。当我没有输入任何字符时,它会打印出来#34;句子是"和#34;解码后的句子是",但是当我输入一个或多个字符时,它只会坐在那里什么都不做。我不认为这可能是MySentence课程的错误,因为它甚至不打印"句子是"。

#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;
}

1 个答案:

答案 0 :(得分:0)

正如上午所建议的那样。尝试在行尾添加一个endl

cout&lt;&lt; &#34;句子是&#34; &LT;&LT; s&lt;&lt; ENDL;

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

一篇可能会有所帮助的有趣帖子 Buffer flushing: "\n" vs. std::endl