Search code examples
cgetchar

C - Print one word per line


I'm trying to make my version of the following C program contained in a famous book of C programming language:

Write a program that print its input one word per line. Here's my code:

#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;
}

To test it, I tried as input:

  • "abc" which the program output as "a".
  • "a b c" which the program output as one letter per line.

It is correct to say, that "abc" was trunked because of getchar() function, which memorize just one character in "c" variable? 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?


Solution

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

    It is not correct, getchar parses char by char, it does not truncate, what is happening is that state only gets assigned IN when a space, newline or tab is inputed.

    Since the execution of putchar(c) depends on state to be equal to IN it never prints anything unless one of those three blank characters is inputed at some point, in whitch case it will print the next character or \n for one of those 3 blank characters.

    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?

    All the 5 characters are read by getchar(), the output will be:

    b 
    c
    

    For the reasons explained in the previous question.

    Footnote

    getchar() should be assigned to an int which is its return type, assigning it to a char is problematic since char may be unsigned and EOF is usually -1.