-3

How does using stringstream to extract an integer value from a string differ from simply using explicit value casting to change the type?

Example:

string a = "1234";
int x;
x= int (a);

vs.

string a = "1234";
int x;
stringstream (a) >> x;
Marcel
  • 115
  • 4

1 Answers1

1

Well, major difference is that:

string a = "1234";
int x;
x= int (a);

does not compile, there is no conversion from std::string to int. Modern way to convert std::string to int is to use stoi function, but be carefull with it because it will throw for "x1234" but will hapilly parse: "1234x".

marcinj
  • 48,511
  • 9
  • 79
  • 100
  • Could you explain why it will treat "x1234" and "1234x" differently? – Marcel Jan 09 '16 at 13:52
  • @Marcel its all in the link I provided, `...takes as many characters as possible to form a valid base-n (where n=base) integer number `, and throws std::invalid_argument `if no conversion could be performed`. – marcinj Jan 11 '16 at 10:57