c++qtqtextstream

Qt, QTextStream - inputting a char/string into an int


Consider the following program:

int num;

QTextStream(stdin) >> num;

QTextStream(stdout) << num;

Like this, if I am to incorrectly input a string, or a char, into the variable num, its value becomes 0 by default.

How can I change the behavior of QTextStream, so that it stores a different value for incorrect inputs? For example, -1?


Solution

  • You cannot change this behavior, but you can check QTextStream::status() for QTextStream::ReadCorruptData.

    int num;
    
    QTextStream input(stdin);
    input >> num;
    
    if (input.status() == QTextStream::ReadCorruptData)
        num = -1;
    
    QTextStream(stdout) << num;