c++计算数字字符串的和

来源:互联网 发布:淘宝上最火的店铺 编辑:程序博客网 时间:2024/05/21 14:42

问:输入11  22     333   444 字符串,计算出4个数相加的结果


答:

采用先去除字符串中的重复空格,然后对数字进行相加


#include <iostream>
#include <string>
#include <sstream>
using namespace std;

/*去除字符串中间重复空格的函数,不考虑头尾*/
string remove_surplus_spaces(const string& src)
{
    string result = "";
    for(int i = 0;src[i] != '\0';i++)
    {
        if(src[i] != ' ' )
            result.append(1,src[i]);
        else
            if(src[i+1] != ' ')
                result.append(1,src[i]);
    }
    return result;
}


int func(const string& s,const char c)
{
    unsigned int head = 0;
    unsigned int pos = 0;
    string ssub;
    int ret = 0 ,temp;
    
    while((pos=s.find(c,head))!=string::npos)
    {
        ssub = s.substr(head,pos-head+1);
        
        stringstream ss(ssub);   //将字符串转换为数字
        ss >> temp;
        ret += temp;
        head = pos+1;
    }
    if(head<s.length())
    {
        ssub = s.substr(head,s.length()-head+1);
        stringstream ss(ssub);
        ss >> temp;
        ret += temp;
    }
    return ret;
}


int main()
{
    string input;
    string output;
    int result;
    getline(cin,input);   //输入带空格的字符串


    output = remove_surplus_spaces(input);
    result = func(output,' ');
    cout << result << endl;
    
    return 0;
}


更简洁的解法:

#include <iostream>


using namespace std;


int main()
{
    int i,result = 0;
    while(cin >> i)
    {
        result += i;
        while(cin.peek()==' ')
        {
            cin.get();
        }
        if(cin.peek()=='\n')
            break;
    }
    
    cout << "result:" << result << endl;
}


根据空格直接区分输入的数字

#include <iostream>

using namesapce std;

int main()

{

int i, result = 0;

do{

     cin >> i;

     result += i;

}while(cin.get!='\n');

cout << "result: " << result << endl;


return 0;

}

原创粉丝点击