Splitting a C++ std::string using tokens

Last Updated On Wednesday 27th Oct 2021

std string split

I find std::getline() is often the simplest. The optional delimiter parameter means it’s not just for reading lines.

	#include <sstream>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<string> strings;
    istringstream f("denmark;italy;spain;germany");
    string s;    
    while (getline(f, s, ';')) {
        cout << s << endl;
        strings.push_back(s);
    }
}
	
	denmark
italy
spain
germany
	

std::string split

	#include <string>
#include <iostream>
#include <sstream>

int main() {
    // read file line by line
    std::istringstream input;
    input.str("1\n2\n3\n4\n5\n6\n7\n");
    int sum = 0;
    for (std::string line; std::getline(input, line); ) {
        sum += std::stoi(line);
    }
    std::cout << "\nThe sum is: " << sum << "\n\n";

    // use separator to read parts of the line
    std::istringstream input2;
    input2.str("a;b;c;d");
    for (std::string line; std::getline(input2, line, ';'); ) {
        std::cout << line << '\n';
    }
}
	
	The sum is: 28

a
b
c
d
	

std split