【发布时间】:2011-01-20 06:46:36
【问题描述】:
是否可以在 Qt 中使用cin?我可以使用 cout,但找不到如何在 Qt 控制台应用程序中使用 cin 的示例。
【问题讨论】:
是否可以在 Qt 中使用cin?我可以使用 cout,但找不到如何在 Qt 控制台应用程序中使用 cin 的示例。
【问题讨论】:
我测试了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.
换句话说,你并不需要 QFile 作为你的中间人。
【讨论】:
是的,虽然您可以做一些事情,例如使用线程,但它可能会按预期工作,这可能会导致这种方法出现问题。
不过,我会推荐一种更惯用 (Qt) 的方式从标准输入读取:
QString yourText;
QFile file;
file.open(stdin, QIODevice::ReadOnly);
QTextStream qtin(&file);
qtin >> yourText;
【讨论】:
我刚刚使用 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();
}
希望对你有所帮助!
【讨论】: