可以用Qt使用cin吗?

gra*_*ant 10 c++ qt iostream cin

可以cin在Qt中使用吗?我可以使用cout但无法找到如何cin在Qt控制台应用程序中使用的示例.

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作为你的中间人.


Kal*_*son 8

是的,它可以并且按预期工作,尽管你可以做一些事情,比如使用线程,这可能会导致这种方法出现问题.

但是,我建议使用更加惯用(Qt)的方式从stdin读取:

QString yourText;
QFile file;
file.open(stdin, QIODevice::ReadOnly);
QTextStream qtin(&file);
qtin >> yourText;
Run Code Online (Sandbox Code Playgroud)


And*_*y M 2

我刚刚使用 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)

}

希望它有一点帮助!

  • 我认为他正在谈论将 cin 与某些 qt 对象一起使用,特别是 QString 而不仅仅是整数。 (2认同)