c ++添加逗号分隔值

时间:2016-10-01 19:36:14

标签: c++ csv stringstream atoi

尝试将字符串中的逗号分隔值添加到一起。我觉得我需要删除逗号。这是stringstream的情况吗?

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

1 个答案:

答案 0 :(得分:1)

我会在while循环中使用istringstreamgetline来分隔(标记化)逗号周围的字符串。 然后只需使用std::stoi将每个字符串标记转换为整数,并将该数字添加到总和中。 std::stoi会丢弃字符串输入中的任何空格字符。

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;