実現したいこと
「数値Nが入力します。 位の小さい方から 3 けたごとにカンマ区切りで出力してください。
ただし、Nのけた数は 3 の倍数とは限らない」この実現方法がわかりません
発生している問題・エラーメッセージ
以下のようなコードを書いてみたのですが、
入力が123456789の場合
期待する出力としては123,456,789で
以下のコードで一応出力としては正しく出るのですが、
自分的にあまり納得のいく綺麗なコードとは言えず、
もっといい実現方法があれば教えていただきたいです。
該当のソースコード
C
1#include <stdio.h> 2#include <string.h> 3 4int main(void){ 5 char n[256]; 6 scanf("%s",n); 7 int len=1; 8 for(int i=0;i<strlen(n);i++){ 9 if(len%3==0){ 10 if(n[i+1]!=NULL){ 11 printf("%c,",n[i]); 12 }else{ 13 printf("%c",n[i]); 14 } 15 }else{ 16 printf("%c",n[i]); 17 } 18 len=len+1; 19 } 20 return 0; 21}
※ 質問文を読むと何らかの課題の様なので、参考までに…
そちらの環境が POSIX 2008 に準拠している場合、printf(3) が '(アポストロフィ) フォーマット指示子に対応しているかもしれません。
fprintf - The Open Group Base Specifications Issue 7, 2018 edition IEEE Std 1003.1-2017 (Revision of IEEE Std 1003.1-2008)
https://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html
> (The <apostrophe>.) The integer portion of the result of a decimal conversion ( %i, %d, %u, %f, %F, %g, or %G ) shall be formatted with thousands' grouping characters. For other conversions the behavior is undefined. The non-monetary grouping character is used. 
#include <stdio.h>
#include <locale.h>
int main(void) {
setlocale(LC_NUMERIC, "");
printf("%'d\n", 123456789);
return 0;
}
>自分的にあまり納得のいく綺麗なコードとは言えず
個人的な感覚では他人にはどうすれば納得なのか分かりません。
基準を示していただけますか?

回答3件
あなたの回答
tips
プレビュー