简体   繁体   中英

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM