Created
December 25, 2014 16:13
-
-
Save mitsu-ksgr/2114e5ab4f27eca06874 to your computer and use it in GitHub Desktop.
【C++】数値をカンマ区切りにするヤツ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <iostream> | |
#include <sstream> | |
#include <string> | |
/** | |
* @brief 渡した数値をカンマ区切りの数値文字列に変換します. | |
* @param num 数値 | |
* @param separate_digit 区切り桁数(デフォルト3) | |
* @return 分割した文字列のベクタ | |
*/ | |
std::string convertCommaSeparatedNumber(int n, int separate_digit = 3) | |
{ | |
bool is_minus = n < 0; | |
is_minus ? n *= -1 : 0; | |
std::stringstream ss; | |
ss << n; | |
std::string snum = ss.str(); | |
std::reverse(snum.begin(), snum.end()); | |
std::stringstream ss_csnum; | |
for(int i = 0, len = snum.length(); i <= len;) { | |
ss_csnum << snum.substr(i, separate_digit); | |
if((i += separate_digit) >= len) | |
break; | |
ss_csnum << ','; | |
} | |
if(is_minus) | |
ss_csnum << '-'; | |
std::string cs_num = ss_csnum.str(); | |
std::reverse(cs_num.begin(), cs_num.end()); | |
return cs_num; | |
} | |
int main() | |
{ | |
int n = 1; | |
for(int i = 2; i <= 10; ++i) { | |
printf("%15s, %15s\n", | |
convertCommaSeparatedNumber(n).c_str(), | |
convertCommaSeparatedNumber(-n).c_str()); | |
n = n * 10 + i; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment