检查 QTextStream::运算符>>是否失败

Check if QTextStream::operator>> failed

本文关键字:gt 失败 是否 QTextStream 运算符 检查      更新时间:2023-10-16

sscanf这样的函数返回成功读取的项目数,这对于错误检查很有用,例如下面的代码会打印"failed",因为sscanf会返回3(读取了1,2,3,但"text"不是数字)。

QTextStream是否提供等效的错误检查方法?

const char *text = "1 2 3 text";
int a, b, c, d;
if (4 != sscanf(text, "%d %d %d %d", &a, &b, &c, &d))
    printf("failed");
QString text2 = text;
QTextStream stream(&text2);
stream >> a >> b >> c >> d; // how do I know that d could not be assigned?

您可以通过调用 stream.status() 来查询流在读取后的状态:

if (stream.status() == QTextStream::Ok) 
{
    // succeeded
} 
else
{
    // failed
}

无论如何,sscanf 检查可能还不够:-(

在很多情况下,开发人员会希望寻找更多错误,例如溢出等。

const char *text = "1 2 3 9999999999";
int a, b, c, d;
if (4 != sscanf(text, "%d %d %d %d", &a, &b, &c, &d))
    printf("failed");
printf("Numbers: %d %d %d %dn", a, b, c, d);
// But because of an overflow error, that code can
// print something unexpected, like: 1 2 3 1410065407
// instead of "failed"

辅助字符串可用于检测输入错误,例如:

const char *text = "1 9999999999 text";
QString item1, item2, item3, item4;
QTextStream stream(text);
stream >> item1 >> item2 >> item3 >> item4;
int a, b, c, d;
bool conversionOk; // Indicates if the conversion was successful
a = item1.toInt(&conversionOk);
if (conversionOk == false)
    cerr << "Error 1." << endl;
b = item2.toInt(&conversionOk);
if (conversionOk == false)
    cerr << "Error 2." << endl;
c = item3.toInt(&conversionOk);
if (conversionOk == false)
    cerr << "Error 3." << endl;
d = item4.toInt(&conversionOk);
if (conversionOk == false)
    cerr << "Error 4." << endl;

将打印"错误 2."、"错误 3."和"错误 4."。

注意:cin,cout和cerr也可以定义为:

QTextStream cin(stdin, QIODevice::ReadOnly);
QTextStream cout(stdout, QIODevice::WriteOnly);
QTextStream cerr(stderr, QIODevice::WriteOnly);