tags:

views:

365

answers:

4

within Qt is it possible to use cin?? I can use cout but cannot find anywhere where it shows how to use ciin within a Qt Console application

many thanks,

gda2004

A: 

Yes, you have access to all standard library functions within Qt apps, as far as I know. What exactly is the problem?

JimDaniel
+1  A: 

Hey,

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 !

Andy M
I think he is talking about using cin with certain qt objects especially QString not just ints.
Roman A. Taycher
+5  A: 

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;
Kaleb Pederson
Thank you for such a uesful snippet piece of code.
ShaChris23
And you can do similar with cout (qout). One of the larger benefits is the native support for many Qt types.
Kaleb Pederson
+1  A: 

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.

ShaChris23
Coolbeans. I didn't like the idea of using "stdin" as a fake file.
Mark