45日目 getcharの基本に戻る

K&RのExcersise1-8やろうと思ったらgetchar()も忘れていた。
まずは単語カウント。
単純にカウントしたいならスペース+1じゃないかと考えた。

#include <stdio.h>
main()
{
	int c, ws;

	ws = 0;
	printf("Please type a sentence.\n\n");
	while ((c = getchar()) != '\n')
		if (c == ' ')
			++ws;
	printf("There is %d words.", ws+1);
}

実行結果

Please type a sentence.

Hello, world!
There is 2 words.

でもよく考えたら、

Please type a sentence.

Hello,   world!
There is 4 words.

こういう結果もありうる。これはいかん。というわけでp.20ではstateなる変数が導入されます。

#include <stdio.h>
main()
{
	int c, wc, state;

	wc = 0;
	state = 0;
	printf("Please type a sentence.\n\n");
	while ((c = getchar()) != '\n')
		if (c == ' ')
			state = 0;
		else if (state == 0) {
			state = 1;
			++wc;
		}
		printf("There is %d words.", wc);
}

実行結果

Please type a sentence.

Hello, world!
There is 2 words.
Please type a sentence.

Hello,   world!
There is 2 words.

はい。スペースがいくつあっても大丈夫ですね。

#define IN 1
#define OUT 0

としてstate==の右辺を書き換えてあげればより見やすいという備忘録でした。