cgetcharputchar

print each word on a new line


I am trying to print each word on a new line. I have made it to scan for a space and then print new line. It cansput deletes some letters at times:

#include <stdio.h>
#include <ctype.h>

int main(void)
{
char ch;
int nextChar;
    nextChar = getchar();
    while (ch != EOF) {
        if (ch == ' ') {
            putchar('\n');
        }
        else {
            putchar(ch);
        }
        ch = getchar();
    }
    return 0;
}

For example Input: hello how are you

output:

hello
how
are
you

Solution

  • The issue here is you assign first char value to nextChar variable and use ch variable. To correct try the folowing:

    #include <stdio.h>
    #include <ctype.h>
    
    int main(void)
    {
        char ch = getchar();
        while (ch != EOF) {
            if (ch == ' ') {
                putchar('\n');
            }
            else {
                putchar(ch);
            }
            ch = getchar();
        }
        return 0;
    }