如何在读取无符号整数时检测负数作为解析错误? [英] How to detect negative numbers as parsing errors when reading unsigned integers?

查看:130
本文介绍了如何在读取无符号整数时检测负数作为解析错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个C ++ iostream读取基本10(十进制)表示形式的无符号整数,并且至少需要进行基本的错误检测。在我看来,减号在这种情况下显然是一个错误,因为无符号整数没有符号。然而,gcc有不同的意见:

I want to read unsigned integers in base-10 (decimal) representation from a C++ iostream with at least rudimentary error detection. In my view, minus signs would clearly be an error in this case, because unsigned integers have no sign. However, the gcc is of a different opinion:

#include <iostream>
#include <sstream>

int main() {
    std::stringstream a("5"), b("-0"), c("-4");
    unsigned int i;
    a >> i; if ( a ) std::cout << i << std::endl; else std::cout << "Conversion failure" << std::endl;
    b >> i; if ( b ) std::cout << i << std::endl; else std::cout << "Conversion failure" << std::endl;
    c >> i; if ( c ) std::cout << i << std::endl; else std::cout << "Conversion failure" << std::endl;
    return 0;
}

给我输出

4294967292

已读取有符号整数-4并将其转换为unsigned int。

for the last line, as if a signed integer -4 had been read and converted to unsigned int.

很明显,海湾合作委员会人士认为功能。是否有一些标准要求这种行为,并且没有任何方法写一个自己的解析器脱离它,即检测-4(也许-0)作为转换错误?

Appearently, the GCC people see this as a feature. Is there some standard that mandates this behaviour, and is there any way short of writing an own parser to get out of it, i.e. detect "-4" (and maybe "-0") as conversion errors?

推荐答案

咨询C ++ 03,22.2.2.1.2 / 11,格式继承自 scanf 和朋友,这反过来又说,转换的字符序列是可选地签名的,即使对于具有无符号输出的那些。 strtoul 是一样的。

Consulting C++03, 22.2.2.1.2/11, the formats are inherited from scanf and friends, which in turn all say that the converted character sequence is "optionally signed", even for the ones with unsigned output. strtoul is the same.

所以,我想你可以说的标准要求的行为是C89 C ++ 03,C99 for C ++ 11.

So, I suppose you could say the standard that mandates the behavior is C89 for C++03, C99 for C++11.

由于 - 恰好只允许作为第一个字符,我想这个解决方法是在使用 operator>> 之前用 peek 检查它。

Since the - happens to be allowed only as the first character, I suppose that the workaround is to check for it with peek before using operator>>.

这篇关于如何在读取无符号整数时检测负数作为解析错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆