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;
}
gives me an output of
4294967292
for the last line, as if a signed integer -4 had been read and converted to unsigned int.
Apparently, 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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…