C - 每行打印一个字

C - Print one word per line

我正在努力使我的以下 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;
}

为了测试它,我尝试输入:

“abc”是因为 getchar() 函数,只记住“c”变量中的一个字符,这样说是正确的吗? 这也是正确的,说“a b c”被 getchar() 函数作为单个字符处理了 3 次(迭代时 3 次),因为每个字母之间有一个 space?

It is correct to say, that "abc" was trunked because of getchar() function, which memorize just one character in "c" variable?

不正确,getchar 通过 char 解析 char,它不会 truncate,发生的事情是 state 仅在输入 space、换行符或制表符时分配 IN

由于 putchar(c) 的执行取决于 state 等于 IN 它永远不会打印任何东西,除非在某些时候输入了这三个空白字符之一,在这种情况下它将为这 3 个空白字符之一打印下一个字符或 \n

And it is also correct, say that "a b c" were being processed 3 times (3 while iteration) by getchar() function as single char because of a space between every letter?

getchar()读取所有5个字符,输出将是:

b 
c

由于上一个问题中解释的原因。

脚注

getchar() 应该分配给它的 return 类型的 int,将它分配给 char 是有问题的,因为 char 可能是无符号的EOF 通常是 -1.