Text to number, number to text
#include <iostream>
#include <string>
using namespace std;
int main() {
string a = "25";
string b = "17";
cout << a + b << "\n"; // joins the text: 2517
cout << stoi(a) + stoi(b) << "\n"; // adds the numbers: 42
double price = stod("3.75");
cout << price * 2 << "\n";
string label = "Level " + to_string(5);
cout << label << "\n";
return 0;
}Output
2517 42 7.5 Level 5
| Function | Converts |
|---|---|
stoi(s) | string → int |
stoll(s) | string → long long |
stod(s) | string → double |
to_string(x) | number → string |
Splitting text into words: stringstream
A stringstream (from <sstream>) lets you use >> on a string, just like cin. It's the easy way to split a sentence into words:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string sentence = "the quick brown fox";
stringstream ss(sentence);
string word;
int count = 0;
while (ss >> word) {
count++;
cout << count << ": " << word << "\n";
}
return 0;
}Output
1: the 2: quick 3: brown 4: fox
while (ss >> word) keeps going as long as there is another word to read.
Splitting on a comma: getline with a separator
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string csv = "red,green,blue";
stringstream ss(csv);
string part;
while (getline(ss, part, ',')) {
cout << "[" << part << "]\n";
}
return 0;
}Output
[red] [green] [blue]
Building a string
An ostringstream works like cout, but collects everything into a string:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
ostringstream out;
out << "Player " << 1 << " scored " << 3.5 << " points";
string report = out.str();
cout << report << " (" << report.length() << " characters)\n";
return 0;
}Output
Player 1 scored 3.5 points (26 characters)
Remember: Need numbers out of a line of text? Read the whole line with
getline, then pull values out with astringstream.