题意:
求a+b的和,但是要按指定格式输出。
控制格式的方法是:将计算出的和转化为string来存储,并且获取其长度,从后往前依次插入‘,‘,注意如果结果是负数则终止条件要提前1个
本题学习的技巧有:
1.利用stringstream(注意要include<sstream>)将int转string:(例如将int a 转换为 string s):
stringstream ss; ss << a; ss >> s;
2.向string中插入字符串的方法:
s.insert(pos, str),pos是待插入的位置, str是待插入的字符串
完整代码:
#include <cstdio> #include <iostream> #include <string> #include <sstream> using namespace std; int main() { int a, b, c; string s; scanf("%d%d", &a, &b); c = a + b; stringstream ss; ss << c; ss >> s; int n = s.size(); int temp = 0; if (c < 0) temp = 1; // 注意特判正负号 for (int i = n - 3; i > temp; i -= 3) { s.insert(i, ","); // string里的insert方法能够很好地对在字符串a里插入另一个字符串b } cout << s << endl; return 0; }
原文:https://www.cnblogs.com/Shiko/p/10806629.html