Jump to: navigation, search

The C Programming Language, 2nd Edition, by Kernighan and Ritchie
Exercise 1.12 on page 21

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

Solutions by Richard Heathfield (corrected by FF) and Chrismath.

Richard Heathfield's solution:

#include <stdio.h>

int main(void)
{
    int c;
    int inspace;

    inspace = 1;
    while ((c = getchar()) != EOF) {
        if (c == ' ' || c == '\t' || c == '\n') {
            if (inspace == 0) {
                inspace = 1;
                putchar('\n');
            }
            /* else, don't print anything */
        } else {
            inspace = 0;
            putchar(c);
        }
    }

    return 0;
}

Chrismath's solution:

//ex1-12 
#include <stdio.h> 

#define IN 1 
#define OUT 0 

// print input one word per line 
int main(void) 
{ 
        int c, state; 
        // start without a word 
        state = OUT; 
         
        while ((c = getchar()) != EOF) { 
                // if the char is not blank, tab, newline 
                if (c != ' ' && c != '\t' && c != '\n') { 
                        // inside a word 
                        state = IN; 
                        putchar(c); 
                // otherwise char is blank, tab, newline, word ended 
                } else if (state == IN) { 
                        state = OUT; 
                        putchar('\n'); 
                } 
        } 
        return 0;
}
Personal tools
Personal tools
Tidy_icons
not logged in