0

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 ?

user1948708
  • 43
  • 1
  • 2
  • 10
  • Why'd you do that anyway? Use [`std::stol`](http://en.cppreference.com/w/cpp/string/basic_string/stol) instead. –  Jan 18 '14 at 19:51
  • Problem with that is it raises an exception instead of returning false if the conversion didn't work. I have to know if the string is "invalid" but I don't want the program to stop, and we didn't learn the exception mecanisms yet (it's a practical work for school) so I guess we're not expected to use them. I didn't know about this though, and I may use it anyway, so, thanks ! – user1948708 Jan 19 '14 at 10:23

1 Answers1

3

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))
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Sorry, I copied the one time I got it wrong (and you helped correcting another mistake, thanks^^. But that problem happens with the parentheses at the right place :s – user1948708 Jan 19 '14 at 10:18