如何为每三个数字用逗号分隔整数

时间:2014-03-26 02:14:12

标签: c++

我想输入一个整数,比如123456789,我想输出这样的整数:123,456,789

这是我的代码:

#include <iostream>
#include <stdio.h>
#include <malloc.h>
using namespace std;

char* separate(int);
char* inttostr(int);
int main() {
    int n;
    char* p;
    cin >> n;
    p = separate(n);
    cout << p;
    return 1;
}

char* separate(int num) {
    char* p1, *p2 = inttostr(num), *p3, *pt;
    int count = 1;
    p1 = p2;
    while (*p2++ != '\0');
    p3 = p2 - 1;
    p2 = p2 - 2;
    while (p2 > p1) {
        if (count == 3) {
            pt = p3++;
            while (pt >= p2)
                *(pt + 1) = *pt--;
            *p2 = ',';
            count = 0;
        }
        count++;
        p2--;
    }
    return p1;
}

char* inttostr(int num) {}

我不知道inttostr中接下来要做什么。任何人都可以帮忙吗?非常感谢。

1 个答案:

答案 0 :(得分:2)

这是我的解决方案:

// The inputted number. Keep this as a string, it's easier to deal with.
std::string     input;

// Get the input line.
std::cout << "Input a number:" << std::endl;
std::cin >> input;

// After every third character, we insert a comma. Go backwards so the leftovers are to the left.
for( int i = input.size() - 3; i > 0; i -= 3 )
{
    input.insert(  input.begin() + i, ',' );
}

// Output the number.
std::cout << "The number is: " << input << std::endl;

答案是了解std :: string,停止使用像malloc这样的C函数,除非你实际使用的是C,并避免使用原始指针。抽象很好。