【PAT 甲级】1001 A+B Format (20)(20 分)

题目链接
作者: CHEN, Yue
单位: PAT联盟
时间限制: 400ms
内存限制: 64MB
代码长度限制: 16KB

Calculate a + b and output the sum in standard format – that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

Input

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

Sample Input

-1000000 9
Sample Output

-999,991

思路:
可以特判,这里用到了string流中的ostringstream 。

代码:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    int a,b,ans;
    string str;
    ostringstream stream;
    cin>>a>>b;
    ans=a+b;
    stream<<ans;    ///向stream写入数据
    str=stream.str();///返回stream所保存的string拷贝
    int len=str.size();
    if(ans<0)
    {
        cout<<"-";
        len--;
        str=str.substr(1,len);
    }
    for(int i=len-3; i>0; i-=3)
    {
        str.insert(i,",");
    }
    cout<<str<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/feng_zhiyu/article/details/80849581