Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::stof not throw when passed an argument it cannot convert?

I'm working on a project where I want to accept an input of the form {float}{single-letter-identifier}, for example 15.6E, or 10W.

To do this, I thought that I could take the input string, strip off the last letter and then check to see if a conversion could be performed to float, using std::stof. This would be nested in a try-catch block, and allow me to notify the user of invalid input.

The open-standard of the STL here (page 653) states that std::stof throws:

invalid_argument if wcstod or wcstold reports that no conversion could be performed.

However, it doesn't throw when passed something it cannot convert, e.g. "48East". A code sample to reproduce this behavior is below:

std::wstring szString = L"48East";
try{
     float f = std::stof(szString);
} catch( ... )
{
     std::cout << "test" << std::endl;
}

This is compiled on MSVC10 in debug mode with /Od, so I'm assuming the call is not optimized away.

I'd appreciate any help (or guidance as to where I've misunderstood/misread the spec!).

like image 384
Thomas Russell Avatar asked Jan 17 '23 03:01

Thomas Russell


1 Answers

As I read it, stof converts as much of the input string as it can until it finds something it can't convert. if it can't convert anything it throws invalid_argument.

like image 161
jwismar Avatar answered Jan 18 '23 22:01

jwismar