3

诸如返回成功读取项目数之类的函数sscanf,这对于错误检查很有用,例如下面的代码将打印“失败”,因为 sscanf 将返回 3(读取了 1、2、3,但“文本”不是数字) .

是否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?
4

2 回答 2

7

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

if (stream.status() == QTextStream::Ok) 
{
    // succeeded
} 
else
{
    // failed
}
于 2012-11-29T10:16:00.393 回答
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);
于 2014-01-06T18:02:47.110 回答