%*dについて

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
sow

%*dについて

#1

投稿記事 by sow » 7年前

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について

#2

投稿記事 by あんどーなつ » 7年前

問題を自分なりに簡略化してみました。

コード:

#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について

#3

投稿記事 by あんどーなつ » 7年前

すみません、実行結果をもう一回張ります。

コード:

$ ./a.exe
        20: ABC

box
記事: 2002
登録日時: 13年前

Re: %*dについて

#4

投稿記事 by box » 7年前

あんどーなつ さんが書きました: Visual Studioでできるかはしらないです(GCC拡張仕様の可能性あり)
printfにもともと備わっている機能です。
できない処理系があったら知りたいくらいです。
バグのないプログラムはない。
プログラムは思ったとおりには動かない。書いたとおりに動く。

アバター
みけCAT
記事: 6734
登録日時: 13年前
住所: 千葉県
連絡を取る:

Re: %*dについて

#5

投稿記事 by みけCAT » 7年前

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.
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)

あんどーなつ

Re: %*dについて

#6

投稿記事 by あんどーなつ » 7年前

boxさん
みけCATさん

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

sow

Re: %*dについて

#7

投稿記事 by sow » 7年前

すいません、返信が遅れました。
あんどーなつさん、みけCATさん、boxさん
レスいただきありがとうございます!!凄く助かりました!!!!

閉鎖

“C言語何でも質問掲示板” へ戻る