2014-03-26 2 views
1

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에서 다음에 무엇을 해야할지하지 않습니다. 누구든지 도울 수 있습니까? 고마워.

// 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; 

대답은, 표준 : : 문자열에 대해 배울 실제로 C를 사용하지 않는 malloc에 ​​같은 C 함수의 사용을 중지하고 원시 포인터를 방지하는 것입니다 :

답변

2

여기 내 솔루션입니다. 추상화가 좋습니다.

+0

감사합니다. 귀하의 솔루션은 완벽합니다. 그러나 포인터를 배우려는 열망하고 있기 때문에이 미완성 코드로이 질문을 이해할 수 있습니까? 좋아요, 숙제이고 해결할 방법이 없습니다. .고맙습니다. – zhean1874

+0

std :: to_string을 사용하여 int에서 문자열로 변환 할 수 있습니다. 너 자신을 inttostr해야합니까? – Ben

+0

좋습니다, 감사합니다 : D – zhean1874

관련 문제