Tuesday, November 27, 2012

Exercise 1-12 Write a program that prints its input one word per line

Kernighan & Ritchie - The  C  Programming Language (Second Edition)

Chapter 1

Exercise 1-12 Write a program that prints its input one word per line

This exercise is very interesting, because it gives you an important piece of information about how the input and output are read and stored.

The solution:


/*----------------------------------------------------------------*/
#include <stdio.h>
int main () {   


    int c;
    while((c = getchar()) != EOF)
    {
        if(c == ' ' || c == '\t' || c == '\n')
            putchar('\n');
        // flush the output!!!
        else
        // store the output!!!
            putchar(c);
       
    }

return 0;
/*----------------------------------------------------------------*/


So how this program really works?
In order to figure out, you have to know something that is NOT reported in K&R2.

Every time you type something into the console, this IS NOT read immediately by your program.
Instead, it is stored in a buffer memory until a special input is inserted!
This input is the newline.

The newline tells the Operating System (NOT YOUR PROGRAM) something like: "OK dude I typed everything I wanted and NOW pass it to my program so it can process it."

The same is also true for the output. Nothing really happens on the console until the special character '\n' is given to the operating system.

If you have understood my highly informal explanation, now you should be able to figure out how my solution works.

You type all your text, including words, tabs, blanks and, eventually, you press ENTER on your keyboard.

When the Operating System receives the newline command, it sends everything to your program that is now able to process, character by character, all your input.

During the processing, every character that is NOT a blank, a tab or a newline, is stored in a buffer for future release to the console. On the other hand, when the program encounters a blank, a newlines or a tab it gives the command ENTER to the operating system, that flushes ALL the content that has been stored previously in the buffer.

That's it.

For more information, please refer to A. Koenig and B.E. Moo - Accelerated C++ Practical Programming be Example - Chapter 1.


As always, if you like this post .... consider to offer me a coffee ;)

No comments:

Post a Comment

Your comment will be visible after approval.