读书笔记-编写一个程序,以每行一个单词的形式打印输入

K&R C语言程序设计(第2版·新版)练习1-12

题目要求:编写编写一个程序,以每行一个单词的形式打印其输入。

习题解答上的答案:

#include 
#define IN 1 /*inside a word*/
#define OUT 0 /*outside a word*/
/*print input one word per line*/
main()
{
	int c, state;

	state = OUT;
	while ((c = getchar()) != EOF)
	{
		if (c == ' ' || c == '\n' || c == '\t'){
			if (state == IN)
			{
				putchar('\n'); /*finish the word*/
				state = OUT;
			}
		}else if (state == OUT) {
				state = IN; /*beginning of word*/
				putchar(c);
			}
			else  /*inside a word*/
				putchar(c);
	}
}

我自己也编写了一段。

#include 
#define IN 1
#define OUT 0
main()
{
	int c,state;

	state = OUT;
	while ((c = getchar()) != EOF)
	{
		if (c == ' ' || c == '\n' || c == '\t')
		{
			if (state = IN)
			{
				printf("\n");

			}
			state = OUT;
		}
		else
		{
			state = IN;
			putchar(c);
		}
	}
	return 0;
}

GitHub上的答案:

https://github.com/caisah/K-and-R-exercises-and-examples

#include 

main()
{
	/* Write a program that prints its input one word per line. */
		int c;

		while ((c = getchar()) != EOF)
			if ((c == ' ') || (c == '\n') || (c == '\t'))
				printf("\n");
			else
				putchar(c);
	return 0;
}

自己没有跳出作者的模板,GitHub上写的最简洁。

你可能感兴趣的:(C语言学习)