检查 QTextStream::运算符>>是否失败
Check if QTextStream::operator>> failed
像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);
相关文章:
- 如果没有malloc,链表实现将失败
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 视图中的参数推导失败:take_while
- 链接到自行创建的dll失败
- 带有特殊路径部分的"std::filesystem::weakly_canonical"失败
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- gcc和c++17的过载解析失败
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- 在WSL:configure_file上对config_file的每次调用都失败:配置文件时出现问题
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 链接阶段在Ubuntu上失败,但在MacOS上失败
- 从父数组测试用例构造二叉树失败
- LibGit2 SSH身份验证失败
- 如何让LLDB在成功时退出,在失败时等待
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- 生成MRPT库时cmake配置失败
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败