Showing posts with label stdout. Show all posts
Showing posts with label stdout. Show all posts

Wednesday, May 13, 2015

Exiting c program right after reading one line or after carriage return while reading input from stdin

Yesterday, we learnt about "C program that copies its input to its output one character at a time" , if you observe the program mentioned in this post, you will observe that we are taking the input from stdin (standard input) and outputting to stdout (each line) till EOF (End of the file) is reached.

Ideally stdin EOF is like forever. So, we end up pressing Ctrl+C to exit the program. Now to modify this program to exit right after one line or after a carriage return, we need to do a simple modification.
Replace EOF with '\n'. Yes its as simple as that.

 #include <stdio.h>  
 int main()  
 {  
   int c;  
   printf("Program exits after new line or carriage return \n");  
   printf("Start your input \n");  
   c = getchar();  
   while(c != '\n')  
   {  
     putchar(c);  
     c = getchar();  
   }  
 }  

Only difference you observe is in the while condition, "while(c != EOF) is changed to while(c != '\n')".

Output will be as below.

 mrtechpathi@mrtechpathi:~/Study/C/K_and_R$ ./a.out   
 Enter Ctrl+C is to exit  
 Start your input   
 just one line input  
 just one line input  
Hope you understood this simple concept !!!