尝试将字符串中的逗号分隔值添加到一起。我觉得我需要删除逗号。这是stringstream的情况吗?
string str = "4, 3, 2"
//Get individual numbers
//Add them together
//output the sum. Prints 9
答案 0 :(得分:1)
我会在while循环中使用istringstream
和getline
来分隔(标记化)逗号周围的字符串。
然后只需使用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;