K&R C Exercise 1-12 Solution

/*
 * Exercise 1-12 Write a program that prints its input one word per line.
 *
 * fduan, Dec. 07, 2011
 */
#include <stdio.h>

#define IN		1
#define OUT		0

int main()
{
	int c, state, nw;
	
	state = OUT;
	nw = 0;

	while( ( c = getchar() ) != EOF )
	{
		if( c != ' ' && c != '\n' && c != '\t' ) 
		{
			state = IN;
			putchar( c );
		}
		else if( state == IN )
		{
			state = OUT;
			putchar( '\n' );
			++nw;
		}
	}
	printf( "Number of Words: %d\n", nw );
	return 0;
}
第二种思路,每次记录前一个字符,当前一个字符为非空格、非制表符、非换行符且当前字符为合法字符时,输出换行符,并将统计单词数量的变量增一。
int main()
{
	int c, lastc, nw;
	
	lastc = ' ';
	nw = 0;

	while( ( c = getchar() ) != EOF )
	{
		if( c != ' ' && c != '\t' && c != '\n' )
		{
			putchar( c );
		}
		else if( lastc != ' ' && lastc != '\t' && lastc != '\n' )
		{
			putchar( '\n' );
			++nw;
		}
		lastc = c;
	}
	printf( "Number of words: %d\n", nw );
	return 0;
}

你可能感兴趣的:(K&R C Exercise 1-12 Solution)