gpt4 book ai didi

C++ 添加逗号分隔值

转载 作者:行者123 更新时间:2023-11-30 05:22:07 26 4
gpt4 key购买 nike

尝试将字符串中的一些逗号分隔值加在一起。我觉得我需要删除逗号。这是 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;

关于C++ 添加逗号分隔值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39810726/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com