Lesson 49 +10 XP

Numbers and Strings

Numbers and Strings

Strings hold text; numbers hold math. When the two meet, C++ picks one side - and it never guesses for you.

String + number is not math

string x = "10";
int y = 20;
string z = x + y;   // error: cannot add string and int

C++ will not silently turn the number into text. "10" and 20 do not add up to "1020" - the program does not even compile.

Converting a number to a string: std::to_string

int score = 42;
string message = "Score: " + to_string(score);
cout << message << endl;   // Score: 42

std::to_string(n) turns a number into a string so the + works.

The other direction is not automatic either

string s = "99";
int n = stoi(s);   // needs <string>, converts to 99

Reading a number out of a string requires a helper like stoi. Nothing happens by magic.

Reading caveat

When you read with cin >>, the stream stops at whitespace. If the user types 10 20, two cin >> reads grab 10 then 20. The stream delivers tokens, not a full sentence.

TL;DR

  • string + int is a compile error, not a sum.
  • Convert numbers to text with std::to_string(n).
  • stoi(s) parses a string into an int.
  • cin >> reads one whitespace-separated token at a time.