Jaspreet Singh
Jaspreet Singh

Reputation: 23

getchar() working in C

getchar() inside while loop takes input after printing whole string. Can anyone explain how getchar() and putchar() works?

I am including following code snippet and output. Also unable to understand behavior of this code

#include <stdio.h>

int main(int argc, char **argv)
{
    int c ;
    c = getchar();
    while(c!=EOF){
        putchar(c);
        printf("%d\n",EOF);
        printf("before getchar in while loop");
        c=getchar();
        printf("after getchar in while loop");
        printf("jas\n");
    }
    return 0;
}

Output

Upvotes: 0

Views: 201

Answers (2)

DrC
DrC

Reputation: 7698

getchar is eventually being handled through to the console input management routines. These routines, in a default config (no ioctl or equivalent calls), will read and echo the entire line before returning the string to the program for processing. Once returned, getchar will be prepared to process the entire line before it goes back to the console input routines.

Upvotes: 1

Harshit kyal
Harshit kyal

Reputation: 350

The int getchar(void) function reads the next available character from the screen and returns it as an integer. This function reads only single character at a time. You can use this method in the loop in case you want to read more than one character from the screen.

The int putchar(int c) function puts the passed character on the screen and returns the same character. This function puts only single character at a time. You can use this method in the loop in case you want to display more than one character on the screen. Check the following example −

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

   int c;

   printf( "Enter a value :");
   c = getchar( );

   printf( "\nYou entered: ");
   putchar( c );

   return 0;
}

When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads only a single character and displays it as follows −

$./a.out
Enter a value : this is test
You entered: t

reference : https://www.tutorialspoint.com/cprogramming/c_input_output.htm

Upvotes: 0

Related Questions