检查QTextStream :: operator>>失败

时间:2012-11-29 10:14:32

标签: c++ qt

sscanf这样的函数返回成功读取的项目数,这对于错误检查很有用,例如下面的代码会打印“失败”,因为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?

2 个答案:

答案 0 :(得分:6)

您可以在阅读后通过致电stream.status()来查询stream's status

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

答案 1 :(得分:0)

无论如何,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 %d\n", 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);