5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

stdio

Last updated at Posted at 2014-11-04

//==================================================
// char IO 
//==================================================

const char* str = "10%off";

printf(str);    // 'str' に %文字が入っているのでおかしくなる	 

printf("%s\n", str); // 問題なくなった。
puts(str); // こちらも問題ない。かわりに期待していない場合でも改行が出力される。
while( putc(*str++, stdout) ); // これで期待しない改行の出力はなくなった。

/* ただputcの第二引数に指定するファイルは、
 マクロとして定義されている場合、2回評価される可能性がある。*/

fputc(str, stdout); // こっちのほうが楽、副作用もない。
	
//---------------------------------------------------

# define LEN_MAX 80
char ch[LEN_MAX] = {0};

printf("%s", "what is your name? ");
gets(ch); // 読み取るサイズが固定されている保証がなければ危険。原則:つかわない。

/* 読み取るサイズに制限をつける */

int i=0;
// 最大で80文字 改行文字まで入力を促す。
for( ; ch[i-1] != '\n'; i = strlen(ch) ) {
	fgets(ch, LEN_MAX, stdin);
}

// 読み取るフィールド幅に制限
scanf("%79s", ch);

//====================================================
// フォーマットIO 
//====================================================
// 出力する文字数(精度)に制限
printf("%.*s\n", LEN_MAX, ch);

// スキャン集合で4桁の数字を読み取り。数字以外の読み取りがあると修復不能(?)
scanf("%4[0-9]s");

//====================================================
// ちょっと型指向
//====================================================
// 数値のみ読み取る
int n;
while( scanf("%d", &c) <= 0 ) n = getchar(); // ストリームを進める(強引?)

//---------------------------------------------------
// おとなしくsscanf()

char str[80] = {0};

fputs("? ", stdout);
scanf("%79s", str);

int i, n, c = 0;

// 読み取った文字列中に数字以外が含まれているか。
for(i = 0; i < strlen(str); ++i) {
	if(isdigit(str[i])) ++c;
}
if(c == strlen(str)) {
	sscanf(str, "%d", &n);
	printf("%d\n", n);
}
else {
	puts("not a number");
}
/* もっとまともな書き方がありそう(´・ω・`) */

備考:
・文字として扱える数値のは正の整数のみであることがC言語により決められている。
・プログラム開始時に stdout, stdin, stderr は自動的に開かれる(コンパイル・オプションによる)
・標準ライブラリを利用した入出力はバッファリングされる。
・データブロック単位のIOはまだやってない(´・ω・`)

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?