KTDPMH
KTDPMH

Reputation: 31

how putchar works with while loop?

I am new to c programming, so hope you guys can help me out with such questions.

1. I thought putchar() only print 1 char each time, while when I enter several char like 'hello' it print 'hello' before allow me to enter a next input? I thought that it should print only 'h' and then allow me to enter other input because getchar() only return one character each time.

2. how to make the loop stops? I know EOF has value of -1, but when I enter -1, the loop still runs.

#include <stdio.h>

main()
{   

    int c = getchar();

    while(c != EOF){
        putchar(c);
        c = getchar();
    }

}

Upvotes: 0

Views: 1165

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134346

After the first getchar() has completed reading one character, the next getchar(); is inside the while() loop, so as per the logic, it will keep reading the input one-by-one, until in encounters EOF.

Following the same logic, putchar(c); is under the while loop, so it will print all the characters [one character per loop basis] read by getchar() and stored in c.

In linux, EOF is produced by pressing CTRL+D. When waiting for input, if you press this key combination, the terminal driver will transform this to EOF and while loop will break.

I'm not very sure about windows, but the key combination should be CTRL+Z.

Note: even if it seems entering -1 should work in accordance with EOF, actually it won't. getchar() cannot read -1 all at a time. It will be read as - and 1, in two consecutive iterations. Also worthy to mention, a character 1 is not equal to an integer 1. A character 1, once read, will be encoded accordingly [mostly ASCII] and the corresponding value will be stored.

Upvotes: 1

sandman
sandman

Reputation: 119

  1. getchar() gets the input from the console. In a while loop, it will read all the characters from the input including the return key.

  2. -1 is "-1". It's not a value but just another combination of characters. EOF occurs when there is no more char in the buffer. i.e. when you press Enter (or Ctrl-Z or Ctrl-D depending on your OS)

Upvotes: 0

Related Questions