Code:
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using std::cerr;
using std::cout;
using std::stringstream;
using std::string;
using std::for_each;
void convert(const string& a_value)
{
unsigned short i;
if (stringstream(a_value) >> i)
cout << a_value << " converted to " << i << ".\n";
else
cerr << a_value << " failed to convert.\n";
}
int main()
{
string inputs[] = { "abc", "10", "999999999999999999999", "-10", "0" };
for_each(inputs, inputs + (sizeof(inputs)/sizeof(inputs[0])), convert);
return 0;
}
Output from Visual Studio Compiler (v7, v8, v9, v10):
abc failed to convert. 10 converted to 10. 999999999999999999999 failed to convert. -10 converted to 65526. 0 converted to 0.
Output from g++ (v4.1.2, v4.3.4):
abc failed to convert. 10 converted to 10. 999999999999999999999 failed to convert. -10 failed to convert. 0 converted to 0.
I expected the "-10"
to fail to be converted to an unsigned short
but it succeeds with the VC compilers. Is this a:
- bug in the VC compilers ?
- bug in the GNU compilers and I have an incorrect expectation ?
- an implementation defined behaviour ?