Search code examples
cgetchar

Why is an entire string being read and printed with getchar?


#include <stdio.h>
void main()
{
char c = getchar();
while ( c != '.')
{
putchar(c);
c = getchar();
}
}

when you run above code and input any string like "Shubham jain". the whole string gets copied and gets printed while getchar() should have read only the first character from the string. can someone explain how is this happening?


Solution

  • When you input a string using your program, it will automatically provide input for every char in the string on getchar function, calling it multiple times. The moment the loop detects a '.' the program stops reading any more characters.