【发布时间】:2021-05-26 00:48:30
【问题描述】:
我正在尝试将以下 C 程序的版本包含在一本著名的 C 编程语言书籍中:
编写一个程序,每行打印一个单词。 这是我的代码:
#include <stdio.h>
#define OUT 1
#define IN 0
int main(void){
char c;
int state = OUT; /*Indicates if we are IN a white space, tab, nl or if we are OUT (a simple letter)*/
while ((c = getchar()) != EOF)
{
if (c == ' ' || c == '\n' || c == '\t')
{
state = IN;
putchar('\n');
} else
if(state == IN){
state = OUT;
putchar(c);
}
}
return 0;
}
为了测试它,我尝试作为输入:
- 程序输出为“a”的“abc”。
- “a b c”程序输出为每行一个字母。
正确地说,“abc”是因为getchar()函数而被连接起来的,它只记住“c”变量中的一个字符? 这也是正确的,说“a b c”被 getchar() 函数处理了 3 次(3 次迭代),因为每个字母之间有空格?
【问题讨论】:
-
char c;->int casgetchar返回 int