添加字符串中的所有数字

时间:2016-03-30 18:06:10

标签: c++

我试图添加字符串中的所有数字,但我无法弄清楚如何添加2位数字。 例如:ab32d3 我希望答案是35。 这是我的代码:

int main()
{
int max=0,min=100000,sum=0,totalsum=0;
string s;
ifstream in ("Unos.txt");

while(getline(in,s))
{
    cout<<s<<endl;
    for(int i=0;i<s.length();++i)
    {
        if(s[i]>max)
        {
            max=s[i]-'0';
        }
        if(s[i]<min)
        {
            min=s[i]-'0';
        }
        if(isdigit(s[i]))
        {
            sum=10*sum+s[i]-'0';
        }
        else
        {
            totalsum+=sum;
            sum=0;
        }
    }
}
totalsum+=sum;
cout<<"Najveci broj je: "<<max<<endl;
cout<<"Najmanji broj je: "<<min<<endl;
cout<<"Zbir svih brojeva je: "<<totalsum<<endl;
return 0;

}

2 个答案:

答案 0 :(得分:1)

试试这个:

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main() {
   string str = "ab32d3", temp;
   int sum = 0;

   for ( int i = 0; i < str.size(); i++ ) {
       if ( isdigit(str[i]) ) temp.push_back(str[i]);
       else {
           if ( temp.size() > 0 ) {
               sum += stoi(temp);
               temp = string();
           }   
       }
   }

   // Last number (if exists)
   if ( temp.size() > 0 ) sum += stoi(temp);

   cout << sum << endl;

   return 0;
}

它会打印35

答案 1 :(得分:0)

#include <iostream>
#include <cctype>

int main() {

    std::string s = "ab32d3";
    int value_so_far = 0;
    int total = 0;

    for (int i = 0; i < s.length(); ++i)
    {
        if (isdigit(s[i])) { // This keeps a running total until the number ends
            value_so_far = 10 * value_so_far + s[i] - '0';
        } else { // Here the number has ended - Add to the total and reset
            total += value_so_far;
            value_so_far = 0;
        }
    }

    // Got to the end - Add what is left!
    total += value_so_far;

    std::cout << "Ans:" << total << std::endl;
    // your code goes here
    return 0;
}

以下是链接:ideone code

请检查代码中的注释以解释说明。