siv*_*udh 21
我测试了Kaleb Pederson的答案,并找到了比他提出的解决方案更简洁的方法(尽管我要感谢他指出了我正确的方向):
QTextStream qtin(stdin);
QString line = qtin.readLine(); // This is how you read the entire line
QString word;
qtin >> word; // This is how you read a word (separated by space) at a time.
Run Code Online (Sandbox Code Playgroud)
换句话说,你并不需要QFile作为你的中间人.
是的,它可以并且按预期工作,尽管你可以做一些事情,比如使用线程,这可能会导致这种方法出现问题.
但是,我建议使用更加惯用(Qt)的方式从stdin读取:
QString yourText;
QFile file;
file.open(stdin, QIODevice::ReadOnly);
QTextStream qtin(&file);
qtin >> yourText;
Run Code Online (Sandbox Code Playgroud)
我刚刚使用 QtCreator 尝试了以下代码,它似乎有效:
#include <QtCore/QCoreApplication>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
cout << endl << "hello" << endl;
int nb;
cout << "Enter a number " << endl;
cin>>nb;
cout << "Your number is "<< nb<< endl;
return a.exec();
Run Code Online (Sandbox Code Playgroud)
}
希望它有一点帮助!