新人求代码
计算一系列整数的和问题描述 对于给定的一系列整数,要求计算它们的和
输入说明 输入数据文件有多行,每行上可能有0个,一个或多个整数,直到文件结束
输出说明 输出数据的个数、逗号、空格、总和
输入样例
15 42
51
303
755
输出样例
5, 1166
1 #include <iostream> 2 #include <fstream> 3 #include <string> 4 #include <iterator> 5 using namespace std; 6 7 void add(string &sum, const string &str) 8 { 9 size_t flag = 0;//进位标志 10 size_t tmp, i; 11 size_t sizeSum = sum.size(); 12 size_t sizeStr = str.size(); 13 14 for (i = 0; i<sizeSum && i<sizeStr; ++i) 15 { 16 tmp = (sum[sizeSum - i - 1] - '0') + (str[sizeStr - i - 1] - '0'); 17 //sum[sizeSum - i - 1] = '0' + tmp%10 + flag; 18 sum.replace(sizeSum - i - 1, 1, (string() + static_cast<char>('0'+tmp%10+flag))); 19 flag = tmp/10; 20 } 21 22 if (sum.size() == i && str.size() > i) 23 { 24 for(; i < str.size(); ++i) 25 { 26 tmp = str[sizeStr - i - 1] - '0' + flag; 27 sum.insert(0, (string() + static_cast<char>('0'+tmp%10)).c_str()); 28 flag = tmp/10; 29 } 30 } 31 else if (sum.size() > i && str.size() == i) 32 { 33 for (; i < sum.size(); ++i) 34 { 35 tmp = sum[sizeSum - i - 1] - '0' + flag; 36 //sum[sizeSum - i - 1] = '0' + tmp%10; 37 sum.replace(sizeSum - i - 1, 1, (string() + static_cast<char>('0'+tmp%10))); 38 flag = tmp/10; 39 } 40 } 41 42 // 1 == flag ? sum.insert(0, (string() + static_cast<char>('0'+flag)).c_str()): 0==0; 43 if (1 == flag) 44 { 45 sum.insert(0, (string() + static_cast<char>('0'+flag)).c_str()); 46 } 47 } 48 49 int main(int argc, char **argv) 50 { 51 if (2 != argc) 52 { 53 cout << string("error msg!") << endl; 54 return -1; 55 } 56 string strFile(argv[1]); 57 58 if (strFile.size() == 0) 59 { 60 cout << string("error file msg!") << endl; 61 return -2; 62 } 63 64 ifstream fin(strFile.c_str()); 65 istream_iterator<string> beg(fin), end; 66 string sum, tmp; 67 int i = 0; 68 69 while (beg != end) 70 { 71 ++i; 72 tmp = *beg; 73 add(sum, tmp); 74 ++beg; 75 } 76 cout << "sum = " << sum << endl; 77 cout << "i = " << i << endl; 78 79 return 0; 80 }