Search code examples
c++csvstringstreamatoi

c++ adding comma separated values


Trying to add together some comma separated values from a string. I feel like I will need to remove the commas. Is this a case for stringstream?

string str = "4, 3, 2"
//Get individual numbers
//Add them together
//output the sum. Prints 9

Solution

  • I would use istringstream with getline in a while loop to split (tokenize) the string around commas. Then simply use std::stoi to convert each string token into an integer, and add that number to the sum. std::stoi discards any whitespace characters within the string input.

    std::string str = "4, 3, 2";
    std::istringstream ss(str);
    
    int sum = 0;
    std::string token;
    while(std::getline(ss, token, ',')) {
        sum += std::stoi(token);
    }
    std::cout << "The sum: " << sum;