首页 > 解决方案 > 为什么这段代码会触发一定位数的断点?

问题描述

我想以 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

在这里,我跟踪了 13 位数字的代码。
在此处输入图像描述
在此处输入图像描述
在此处输入图像描述
在此处输入图像描述
在此处输入图像描述
在此处输入图像描述

标签: c++stringvisual-studioruntime-error

解决方案


它对您不起作用的原因在您帖子的评论中。对于答案,以下代码应该为您完成这项工作:

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;

推荐阅读