Is it possible to use cin with Qt?

我的梦境 提交于 2019-12-17 16:46:08

问题


Is it possible to use cin in Qt? I can use cout but cannot find examples of how to use cin within a Qt console application.


回答1:


I tested out Kaleb Pederson's answer, and found a more consise way than the solution he presented (though I have to thank him for pointing me to the right direction):

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.

In other words, you don't really need QFile as your middleman.




回答2:


Yes, it's possible and works as expected although you can do things, like use threads, that may cause problems with this approach.

However, I would recommend a more idiomatic (Qt) way to read from stdin:

QString yourText;
QFile file;
file.open(stdin, QIODevice::ReadOnly);
QTextStream qtin(&file);
qtin >> yourText;



回答3:


I just tried the following code with QtCreator and it seems to be working :

#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();

}

Hope it helps a bit !



来源:https://stackoverflow.com/questions/2321880/is-it-possible-to-use-cin-with-qt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!