C++从字符串中获取数字并进行计算

标签 c++ string count numbers

我必须编写一个程序,从字符串中获取数字,然后对这些数字求和。

示例:字符串测试="12,20,7";结果=50

有人可以帮助我吗?型

 string stringNumber="12,20,7";   
 vector<int> test;
 vector<int> position;
string help;
int br=0;
int a;
for(int x=0; x<stringNumber.length(); x++)
{
    if(stringNumber.at(x) !=';'){          //save numbers
        help=stringNumber.at(x);
        istringstream istr(help);
        istr>>a;
        test.push_back(a);
        br++;
    }
    if(stringNumber.at(x) ==';'){     //save position of ","
        position.push_back(br);
        br++;
    }
}

最佳答案

这是一个不需要保存数字和分隔符位置的可能替代方案。它也不使用 std::stringstream,尽管它可以很容易地重写以使用它而不是 std::atoi()。最后,您可以将您喜欢的分隔符作为第二个参数传递给 compute_sum,默认为 ",":

#include <string>
#include <cstdlib>

int compute_sum(std::string const& s, std::string const& delim = ",")
{
    int sum = 0;
    auto pos = s.find(delim);
    decltype(pos) start = 0;
    while (pos != std::string::npos)
    {
        auto sub = s.substr(start, pos - start);
        sum += std::atoi(sub.c_str());

        start = pos + 1;
        pos = s.find(delim, start);
    }

    if (start != pos + 1)
    {
        auto sub = s.substr(start);
        sum += std::atoi(sub.c_str());
    }

    return sum;
}

这是你将如何使用它:

#include <iostream>

int main()
{
    std::cout << compute_sum("12,20,7");
}

这是一个 live example .

关于C++从字符串中获取数字并进行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15849129/

相关文章:

python - 在 Python 中从字符串中获取主题标签的优雅方法?

关于评论投票的mysql子查询问题

Python:计算文件中一组字符串的出现次数

python - 使用 Python 计算数据框中唯一单词的数量

c - 如何在 C 中将 128 位整数转换为十进制 ascii 字符串?

c# - 如何在 C# 中创建具有动态属性和属性的结构

c++ - 在 Mac OS X (El Capitan) 上安装 Cilk Plus 时出错

python - 如何在 bcc64 项目中嵌入 python?

c++ - 错误 C2084 'Function already has a body'

C#去掉字符串 "Color []"中的字符串部分 "Color [ColorName]"