トップ 差分 一覧 ping ソース 検索 ヘルプ PDF RSS ログイン

C 書式付入出力



目次



記事一覧

キーワード

C 書式付入出力

[Programming C][書式]

 printf、fprintf、sprintf

#include <stdio.h>
int printf(const char *format, ...);
int sprintf(char *s, const char *format, ...);
int fprintf(FILE *stream, const char *format, ...);

  • 様々な型の可変個の引数に書式を設定して出力する。
  • 出力streamの中での各変数の表現方法は、parameter format で制御する。
  • printfは出力を標準出力に書き込む
  • fprintfは出力先がstreamで指定されたstreamになることを除けば、printfと同じ
  • sprintfは、文字列の終わりを示す'\0'を出力につけ、parameter s で指定された文字列に結果を書き込む。

よく使われる変換指定子
変換指定子 意味
%d、%i 整数を10進数で出力
%o、%x 整数を8進数、16進数で出力
%c 文字を出力
%s 文字列を出力
%f 浮動小数点数(単精度)を出力
%e 倍精度浮動小数点数を出力
%g 一般的な形式でdoubleを出力

field指定子の例

#include <stdio.h>

int main()
{
  char s[8] = {'H','e','l','l','o','\0'};
  int num = 1234;
  
  printf("%10s\n",   s);
  printf("%-10s\n",  s);
  printf("%10d\n",   num);
  printf("%-10d\n",  num);
  printf("%010d\n",  num);
  printf("%10.4f\n", 12.34);  printf("%*s\n",    10, s);
}

     Hello
Hello  
      1234
1234      
0000001234
   12.3400
     Hello

scanf、fscanf、sscanf

#include <stdio.h>
int scanf(const char *format, ...);
int fscanf(FILE *stream, const char *format, ...);
int sscanf(const char *s, const char *format, ...);

  • streamから値を読み取り、読み取った値をpointer parameter でわたされた address の変数に格納する。
  • 書式指定文字列の使い方は、printfと同じ。変換指定子もほとんど同じ。



この本からの覚書。



YAGI Hiroto (piroto@a-net.email.ne.jp)
twitter http://twitter.com/pppiroto

Copyright© 矢木 浩人 All Rights Reserved.