Exercise 1.12 - Print the input one word per line

Question

Write a program that prints its input one word per line.

Solution

/*Write a program that prints its input one word per line.*/
#include<stdio.h>

int main() {
    int c;
    c = getchar();
    while (c != EOF) {
        if (c == ' ') {
            putchar('\n');
        }
        else {
            putchar(c);
        }
        c = getchar();
    }
}
Run this

Explanation

In this program, we read the one character at a time and check if the character is a space ‘ ‘, we print newline character, ‘n’ thus going to next line in the output, otherwise we simply print the character c.

Comments by Disqus