问题描述
请考虑这个计划:
#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;
}
我在gcc(4.0.1版Apple Inc. build 5490)在OS X 10.5.6和断言是真的;它无法将-1转换为unsigned short。
I tried this on gcc (version 4.0.1 Apple Inc. build 5490) on OS X 10.5.6 and the assertion is true; it fails to convert -1 to an unsigned short.
然而,在Visual Studio 2005(和2008)中,断言失败,n的结果值与你会期望从一个编译器生成的隐式转换 - 即-1是65535,-2是65534等等。但是,然后它变得奇怪的-32769,它转换为32767。
In Visual Studio 2005 (and 2008) however, the assertion fails and the resulting value of n is the same as what you would expect from an compiler generated implicit conversion - i.e "-1" is 65535, "-2" is 65534, etc. But then it gets weird at "-32769" which converts to 32767.
谁是对的,谁错了?
推荐答案
GCC在Max Lybbert的帖子中声称的行为是基于表格是C + +标准,映射iostream行为到printf / scanf转换器(或至少那是我的读数)。然而,g ++的scanf行为似乎不同于istream行为:
The behaviour claimed by GCC in Max Lybbert's post is based on the tables om the C++ Standard that map iostream behaviour onto printf/scanf converters (or at least that;'s my reading). However, the scanf behaviour of g++ seems to be different from the istream behavior:
#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。
actually prints 65535.
这篇关于stringstream无符号转换打破?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!