Splitting a string in C++

Level 3112 keystrokes

getline with ',' as the third argument reads from the stream up to the next comma. The loop repeats until the stream is empty and prints apple, banana and cherry on separate lines.

C++ code

// A stream that reads from the comma-separated text
1stringstream ss("apple,banana,cherry");
// Holds one piece at a time
2string token;
// Reads up to the next ',' (the comma is dropped); returns false when nothing is left
3while (getline(ss, token, ',')) {
// Prints apple, banana, cherry, one per line
4 cout << token << endl;
5}

Output

apple
banana
cherry
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • ,× 5
  • <× 4
  • ;× 3
  • (× 3
  • )× 3
  • '× 2
  • "× 2
  • {× 1
  • }× 1

More C++ examples at level 3

← C++ typing practice