const std::string str = "-5.73945e-39";
std::istringstream iss(str);
auto vals = std::vector<float>(std::istream_iterator<float>(iss), std::istream_iterator<float>{});
If I compile with Apple clang version 15.0.0 (clang-1500.0.16.10) on my M1 chip Mac, size of vals
is 0, but if I compile with other compilers (using any c++ online playground), the size of vals
is 1.
Apparently the value is out of float
range. Anyone knows whether this is leading to undefined behavior? Thanks!
Local and online c++ playground compiling and running.
No, it is not undefined behavior. If the extraction operation on the stream fails, the failbit should be set, which can be examined by calling iss.fail()
. When this failure occurs, it will also cause the iterator to become equal to the end iterator, stopping the extraction.
So, if there is a parse issue, the iteration will stop before the first invalid value, and you can check this by examining the failbit.
if (iss.fail() ) {
std::cout << "Error occurred\n";
} else {
// Successful path
}
For a more comprehensive list of what each of the state bits mean, see https://en.cppreference.com/w/cpp/io/ios_base/iostate