我正在尝试制作一个包含字符串的小程序,然后以三个字符间隔在其中添加逗号,例如如何格式化货币金额。(即1000变成1000,10000变成10000)。
到目前为止,这是我的尝试,并且几乎可行:
#include <string>
#include <iostream>
using namespace std;
int main() {
string a = "123456789ab";
int b = a.length();
string pos;
int i;
for (i = b - 3; i >= 0; i-=3) {
if (i > 0) {
pos = "," + a.substr(i,3) + pos;
}
}
cout << pos;
return 0;
}
带有示例字符串的输出为:
,345,678,9ab
似乎并不想抓住前1到3个字符。我的代码有什么错?
#include <string>
#include <iostream>
using namespace std;
int main() {
string a = "123456789ab";
int b = a.length();
string pos;
int i;
for (i = b - 3; i > 0; i-=3) {
if (i > 0) {
pos = "," + a.substr(i,3) + pos;
}
}
cout << a.substr(0,i+3)+pos;
return 0;
}
当索引为负数时,表示它不能再组成3组。但是可能剩下1-3个数字。我们需要明确地添加它们
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句