user1948708
user1948708

Reputation: 43

C++ : istringstream conversion to long int doesn't work

My problem is, I want to convert a string into a long int. For that, i use an istringstream that way:

long x;
string lString;
istringstream istr;
getLine(cin, lString);
istr.str(lString);
if(!(istr>>x)) return false; //Edited after answer below

(the conversion and the cin are actually in two different methods, I just put the related code together).

The following code returns false if I type "1", but not if I type "1.0". I could search for . in the string and add it if ther isn't, but isn't there a method to convert string to long ?

Upvotes: 0

Views: 458

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

It's because of the operator precedence. The ! operator has higher precedence than the >> operator, so for the compiler what you have written is

if ((!istr) >> x)

You need to add your own parentheses:

if (!(istr >> x))

Upvotes: 3

Related Questions