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

问:输入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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值