2016-02-23 53 views
4

当我尝试从Qt控制台应用程序获取输入时,该程序无法正常工作。如预期了以下工作:读取输入时Qt控制台应用程序出现问题

#include <QCoreApplication> 
#include <QTextStream> 

QTextStream cout(stdout); 
QTextStream cin(stdin); 

int main() 
{ 
    QString msg("Hello world!"); 
    cout << msg << endl; 

    return 0; 
} 

输出:

Hello world! 

但只要我添加,

... 
int main() 
{ 
    QString msg("Hello world!"); 
    cout << msg << endl; 

    cout << "Enter new message: "; 
    msg = cin.readLine(); 
    cout << endl << msg << endl; 

    return 0; 
} 

输出:

Hello world! 

显示却对程序在显示之前等待输入提示输入文本,而不是首先显示提示,然后阅读输入。输入的文本与输入后的(提示)一起显示。

我一直试图解决这个几个小时无济于事。

回答

3

你应该刷新输出流:

 
cout. flush(); 

这也可以写成

(cout << "Enter new message: ").flush(); 
+0

谢谢,我很感激。我试图冲洗'cin',这显然不起作用。现在我明白了! – daanskitte

1

您也可以使用:

cout << "Enter new message: " << flush; 
  • std::flush刚刚刷新stdout流。
  • std::endl除了向stdout添加新行外,还会刷新流。
相关问题