原题目描述如下:
1001 A+B Format (20 分)
题目的意思是,输入a和b,计算a+b的值,并输出。注意输出结果要使用标准格式,即每三个数字要用 ',' 字符分割。
下面介绍将两数和转换为字符串的解法:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a,b,c;
while(cin >> a >> b)
{
string tmp;
c=a+b;
tmp=to_string(c); //将整数转换为字符串
c=tmp.length()-1;
while(true)
{
c -= 2;
if(c<=0||tmp[c-1]=='-') //如果位置标识小于或等于0,或者当前字符前一字符为'-',则跳出
break;
tmp.insert(c--,1,','); //每隔三个,插入','
}
cout << tmp << endl;
}
return 0;
}