【问题标题】:c++ adding comma separated valuesc++ 添加逗号分隔值
【发布时间】:2016-10-01 19:36:13
【问题描述】:

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

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

【问题讨论】:

  • 你是对的。一种解决方案是 std::istringstream 与 std::getline
  • 欢迎来到 Stack Overflow。你试过什么?

标签: c++ csv stringstream atoi


【解决方案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;

【讨论】:

    猜你喜欢
    • 2021-11-30
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多