stringstream 无符号转换损坏?

2023-12-07

考虑这个程序:

#include <iostream>
#include <string>
#include <sstream>
#include <cassert>

int main()
{
    std::istringstream stream( "-1" );
    unsigned short n = 0;
    stream >> n;
    assert( stream.fail() && n == 0 );
    std::cout << "can't convert -1 to unsigned short" << std::endl;
    return 0;
}

我在 OS X 10.5.6 上的 gcc(版本 4.0.1 Apple Inc. build 5490)上尝试了这个,断言是正确的;它无法将 -1 转换为无符号短整型。

然而,在 Visual Studio 2005(和 2008)中,断言失败,n 的结果值与编译器生成的隐式转换所期望的值相同 - 即“-1”是 65535,“-2”是 65534 等.但是当“-32769”转换为32767时,情况变得很奇怪。

这里谁是对的,谁是错的? (-32769 到底是怎么回事??)


GCC 在 Max Lybbert 的帖子中声称的行为基于 C++ 标准中的表格,这些表格将 iostream 行为映射到 printf/scanf 转换器(或者至少是我读到的)。然而,g++的scanf行为似乎与istream行为不同:

#include <iostream>
#include <cstdio>
using namespace std;;

int main()
{
    unsigned short n = 0;
    if ( ! sscanf( "-1", "%hu", &n ) ) {
        cout << "conversion failed\n";
    }
    else {
        cout << n << endl;
    }
}

实际上打印了 65535。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

stringstream 无符号转换损坏? 的相关文章

随机推荐