harsha
harsha

Reputation: 41

No exception while converting a string with alphabets after decimal point using stod()

#include<iostream>
#include<string>
using namespace std;

int main()
{
    double var;
    string word("20.njhggh");
    var = stod(word);
    cout << var << endl;
    return 0;
}

ouput is: 20

The stod function does not thow a exception for input "20.njhggh". It just ignores the letters after decimal point. How do I trow exception for the above case

Upvotes: 1

Views: 833

Answers (2)

Dai
Dai

Reputation: 155360

stod calls strod, the documentation for strod on cplusplus.com says (emphasis mine):

The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes as many characters as possible that are valid following a syntax resembling that of floating point literals, and interprets them as a numerical value.

In your case it successfully read "20" from the input "20.njhggh" and returned it while ignoring the rest. The stod wrapper function will only throw invalid_argument if nothing could be read at all.

stod has an optional second parameter idx which is set to position of the first character in str after the number was read, so you could use that to detect any non-numeric characters in the string:

string word( "20.njhggh" );


size_t stodStart = distance( word.begin(), find_if_not( word.begin(), word.end(), isspace );
size_t stodEnd;
double var = stod( word, &stodEnd );
if( (stodEnd - stodStart) != word.length() ) throw "String is not entirely a floating-point number";

cout << var << endl;

Note the above code finds the first non-whitespace character first to test the stodEnd value.

Upvotes: 1

eerorika
eerorika

Reputation: 238401

How do I trow exception for the above case

According to the documentation, stod has a second argument:

double      stod( const std::string& str, std::size_t* pos = 0 );

If pos is not a null pointer, then a pointer ptr, internal to the conversion functions, will receive the address of the first unconverted character in str.c_str(), and the index of that character will be calculated and stored in *pos, giving the number of characters that were processed by the conversion.

So, if you want to throw an exception when some of the string wasn't used for the conversion, you can compare *pos with the size of the string:

std::size_t pos;
var = stod(word, &pos);
if (pos < word.size())
    throw some_exception();

Upvotes: 3

Related Questions