문자열에 대한 CS106B 교과서의 예제. 프로그램 감각은 끝에서 3 자리마다 쉼표를 추가하는 것입니다. 입력의 경우 15000 출력은 15,000이어야합니다. 보시다시피, 나는 그보다 짧은 숫자를 무시했습니다.숫자에 쉼표를 추가하는 C++ 프로그램
/*
* File: AddCommas.cpp
* -----------------
*
*/
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
/*Function prototypes*/
string addCommas(string digits);
/*Main program*/
int main(){
while(true){
string digits;
cout << "Enter a number: ";
getline(cin, digits);
if (digits == "") break;
cout << addCommas(digits) << endl;
}
return 0;
}
/*Function: addCommas
*Usage: string addCommas(string digits)
*---------------------------------------
*Adds commas to long digits
*/
string addCommas(string digits){
string result;
if (digits.length() > 3){
int t = 0;
for(int i = digits.length() - 1; i >= 0; i --){
result = digits[i] + result;
t++;
if(t%3 == 0){
result = ',' + result;
}
}
if(result[0] == ','){
result.erase(0, 1);
}
} else {
result = digits;
}
return result;
}
당신은 [예를 들어이보기] 표준 라이브러리의 로케일 기능을 사용하여보다 일반적인 솔루션을 선택 할 수 있습니다 (http://en.cppreference.com/w/cpp/locale/num_put). 그것은 훨씬 더 견고합니다. – WhozCraig
숙제? 누군가가 이것을 닫습니까? – Alex