c++从字符串中获取数字并进行计算
C++ take numbers from string and make calculation
我必须写一个程序,从字符串中取出数字,然后求这些数字的和。
示例:string test="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");
}
下面是一个实例
相关文章:
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 使用正则表达式C++计算数字中的十进制空格
- 此代码如何计算数字的奇偶校验?
- 如何计算数字 x 的频率
- 计算数字范围内特定数字的出现次数
- 递归函数,用于计算数字中的位数
- 我正在尝试编写一个函数来计算C++数字的数字根,但在编译后出现错误
- 努力理解一个以十六进制、十进制、bin 和 dec 计算数字总和的程序
- 在C 中计算数字的问题
- 在一系列数字的间隔内计算数字
- 计算数字的幂
- 用递归计算数字的位数
- C++,计算正数和负数并计算数字的平均值)编写一个读取未指定数量的整数的程序
- 如何在 c++ 中计算数字的第 3 个根
- 计算数字中偶数位数
- 计算数字平方根的程序
- 计算数字x的位数,其数字和等于x*m的数字和
- 是否有可能在编译时计算数字的阶乘,但不使用枚举?
- 计算可被 K 整除的范围内的数字,并在范围内计算数字之和
- 不使用字符串计算数字中的数字