c++ - 为什么这段代码会触发一定位数的断点?
问题描述
我想以 3×3 分隔给定数字的数字。
输入:1234567
输出:1,234,567
我写了以下代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string StringIn;
string::iterator it1, it2;
cout << "Enter a number with any number of digits: ";
cin >> StringIn;
unsigned int len = StringIn.length();
it1 = StringIn.end();
if (len % 3 == 0)
for (int i = 1; i < len / 3; i++)
{
it2 = it1 - 3 * i;
StringIn.insert(it2, ',');
}
else
for (int i = 1; i <= len / 3; i++)
{
it2 = it1 - 3 * i;
StringIn.insert(it2, ',');
}
cout << StringIn << endl;
system("pause");
return 0;
}
正如您在下面的照片中看到的,该代码适用于一个数字
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 位数
16, 17, 18, 19, 20, 21, 22, 23, 24 位数
32, 33, 34, 35, 36 位数
但它会触发特定位数的断点。这些特定数量的数字是 13、14、15、25、26、27、28、29、30、31
解决方案
它对您不起作用的原因在您帖子的评论中。对于答案,以下代码应该为您完成这项工作:
string str;
string::iterator it;
cout << "Enter a number with any number of digits: ";
cin >> str;
if (str.size() > 3) {
it = str.end() - 3; // Take the first place where there should be a comma
while (it > StringIn.begin()) { // Make sure that you are still in a string's place
if (it - str.begin() > 3)
it = str.insert(it, ',') - 3; // Insert a comma in the right place, and move to the next comma place
else it = str.begin();
}
}
cout << str << endl;
推荐阅读
- angularjs - Chrome 开发工具未映射 ts 源
- facebook - iOS facebook图形批量请求第一个请求不起作用
- javascript - vba 用 Excel 数据填充 Internet Explorer 表单
- php - Laravel 多次插入不起作用说“插入值列表不匹配”
- django - Django 用户帐户删除然后返回重定向和渲染
- azure-cosmosdb - CosmosDB 查询日期范围 + 索引
- vbscript - 在命令提示符中模拟输入键不起作用
- vue.js - 无法挂载组件
- bash - 如何让期望等待 exec 直到输出结果
- jquery-ui - 使用 JQuery ui 拖放 Div 列和 Div 行