コンマを挿入する
ちょっと頼まれて考えたんだけど、Cがわかってないので結構頭捻ってしまった。
で、結局超頭悪そうなのができてしまった・・・。 Perlだったら1行なんだけどなぁ。
#include <stdio.h> #include <string.h> int main(){ char x[100]; int len; // 入力を受け取る scanf("%s", x); len = strlen(x); // -のとき if(x[0] == '-'){ printf("-"); strcpy(x, x+1); len--; } // 3桁以下ならそのまま出力 if( len <= 3 ) printf("%s", x); else { int h = len % 3 /* xのけた数/3の余り */; int t = 0; if( h > 0 ) while( t < h ) printf("%c", x[t++]); while( t < len ){ printf(",%c%c%c", x[t], x[t+1], x[t+2]); t += 3; } } return 0; }