If you run the following code
#include <string>
#include <sstream>
#include <iostream>
int main() {
std::string small = "9223372036854775807";
std::string s = "9223372036854775808";
{
std::istringstream stream(small);
std::int64_t i;
stream >> i;
if (stream) {
std::cout << "ok" << std::endl;
}
std::cout << stream.fail() << std::endl << i << std::endl;
}
{
std::istringstream stream(s);
std::int64_t i;
stream >> i;
if (!stream) {
std::cout << "error" << std::endl;
}
std::cout << stream.fail() << std::endl << i << std::endl;
}
return 0;
}
you will see that you cannot parse the number into a std::int64_t
and that the stream correctly reports an error. You just cannot read a number that is larger than the maximum number into a std::int64_t
.
In general, integer overflow is undefined behavior in C++, so
When you add in C++ too number that will have a result bigger than the
maximum of int_64, I go in negative values.
is not true for signed integer arithmetics. If you need that you must resort to unsigned arithmetics.
As Aconcagua points out in the comment operator>>
for std::uint64_tdoes not wrap-around, so you could read a
std::uint64_tif the numbers are smaller than
numeric_limits::max()and [convert it to
int64_t`]2. If the number are larger, you probably need to implement a custom type for big integers (or use an existing implementation, e.g. The GNU
Multiple Precision
Arithmetic Library.