我必须编写一个从字符串中提取数字然后将这些数字求和的程序。
例如:string test =“ 12,20,7”;结果= 50
有人能帮我吗? ty
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。