Tuesday, May 12, 2015

C program that copies its input to its output one character at a time

I have been blogging few interesting how-to articles which I learn in my daily professional life. Its been a while I haven't blogged any.So, thought of just adding atleast a program per day (very challenging isn't ?) along with how-to articles.

I will start with C-programming. As everyone know "Kernighan & Ritchie" (K&R) is the best book to learn C programming. I will using examples in this book.


If you want any C snippet meanwhile, just drop me a comment will try and get it done for you.  I cant promise, but will try my best to do code for you.


Frist lets start with "C program that copies its input to its output one character at a time"


 #include <stdio.h>  
 int main()  
 {  
   int c;  
   printf("Enter Ctrl+C is to exit\n");  
   printf("Start your input \n");  
   c = getchar();  
   while(c != EOF)  
   {  
     putchar(c);  
     c = getchar();  
   }  
 }  

Above program is exact copy of a program in K&R, I have just added two printf statements to it.

When you compile and run this program, it accepts whatever the character you input from the keyboard and print them once you press enter (new line / carriage return).

It does this task forever because we have used "While( c != EOF )" in our above code snippet.
This while statements will be true till you reach EOF of stdin (standard input) which is forever.

So, in order to exit from running your program, you need to press "Ctrl+C" on your keyboard together.

Now lets run and see, output will be as below
 mrtechpathi@mrtechpathi:~/Study/C/K_and_R$ ./a.out   
 Enter Ctrl+C is to exit  
 Start your input   
 we are  
 we are  
 trying to print  
 trying to print  
 character by character  
 character by character  
 ^C  
Hope you learnt something new :).

No comments:

Post a Comment