ページ 11

%*dについて

Posted: 2016年10月26日(水) 13:52
by sow
sprintf(s,"%*d: %s",digit(l),i * up + start,tmp);の%*dは何を意味しているか教えていただきたいです。

tmpが%sの部分に入っているのは理解できるのですが、digit(l)とi * upの2つがこの場合はどこに入っている扱いになるのかが理解できないです。
i,up,startはint型です。
tmpはchar型のポインタです。

digitの関数の中身は
return (int)ceil(log10(x+1));
の一文のみです。

Re: %*dについて

Posted: 2016年10月26日(水) 14:05
by あんどーなつ
問題を自分なりに簡略化してみました。

コード:

#include <stdio.h>

int main() {
  char s[10][32];
  sprintf(s[5], "%*d: %s", 10, 20, "ABC");
  printf("%s\n", s[5]);
  return 0;
}
実行結果
$ ./a
20: ABC

ということは、%*dは1つめの引数分だけ右揃えでフォーマットして、
2つめの引数を表示するという意味らしいですね。
Visual Studioでできるかはしらないです(GCC拡張仕様の可能性あり)

Re: %*dについて

Posted: 2016年10月26日(水) 14:06
by あんどーなつ
すみません、実行結果をもう一回張ります。

コード:

$ ./a.exe
        20: ABC

Re: %*dについて

Posted: 2016年10月26日(水) 14:36
by box
あんどーなつ さんが書きました: Visual Studioでできるかはしらないです(GCC拡張仕様の可能性あり)
printfにもともと備わっている機能です。
できない処理系があったら知りたいくらいです。

Re: %*dについて

Posted: 2016年10月26日(水) 22:23
by みけCAT
printf系の関数では、出力幅や精度のかわりに*を用いることで、出力するデータの前に置くint型の引数でそれらの値を指定することができます。

N1570 7.21.6.1 The fprintf functionの5より引用
As noted above, a field width, or precision, or both, may be indicated by an asterisk. In
this case, an int argument supplies the field width or precision. The arguments
specifying field width, or precision, or both, shall appear (in that order) before the
argument (if any) to be converted. A negative field width argument is taken as a - flag
followed by a positive field width. A neg ative precision argument is taken as if the
precision were omitted.
N1570 7.21.6.6 The sprintf functionの2より引用
The sprintf function is equivalent to fprintf, except that the output is written into
an array (specified by the argument s) rather than to a stream.

Re: %*dについて

Posted: 2016年10月27日(木) 10:47
by あんどーなつ
boxさん
みけCATさん

このスレッドの件、適当に回答してしまって申し訳ないです。
以後気を付けるようにいたします。

Re: %*dについて

Posted: 2016年10月28日(金) 18:30
by sow
すいません、返信が遅れました。
あんどーなつさん、みけCATさん、boxさん
レスいただきありがとうございます!!凄く助かりました!!!!