Leo*_*eon 1 c++ qt4 qtextstream
这是一个非常简单的应用程序来说明我遇到的问题。
#include <QTextStream>
int main()
{
QTextStream cin(stdin);
QTextStream cout(stdout);
QString test;
cout << "Enter a value: ";
cout.flush();
cin >> test;
cout << "Enter another value: ";
cout.flush();
test = cin.readLine();
cout << test;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我希望执行暂停并等待输入test = cin.readline();,但事实并非如此。如果我删除cin >> test;然后它暂停。
为什么这段代码的行为是这样的,我如何获得我想要的行为?
可能缓冲区仍然有一个'\n'被接受的结束符cin.readLine();-cin.flush()在执行 cin.readLine() 之前尝试刷新它。
此代码正在工作:
QTextStream cin(stdin);
QTextStream cout(stdout);
QString test;
cout << "Enter a value: ";
cout.flush();
cin >> test;
cout << "Enter another value: ";
cout.flush();
cin.skipWhiteSpace(); //Important line!
test = cin.readLine();
cout << test;
return 0;
Run Code Online (Sandbox Code Playgroud)
您只需要添加cin.skipWhiteSpace()before cin.readLine(),正如我之前所说的 '\n' 字符仍在缓冲区中并且该方法正在摆脱它。