c++中添加逗号分隔值

c++ adding comma separated values

本文关键字:分隔 添加 c++      更新时间:2023-10-16

尝试从字符串中添加一些逗号分隔的值。我觉得我需要去掉逗号。这是stringstream的情况吗?

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

我会在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;