简体   繁体   中英

getchar() != EOF K&R

I'm very sorry for asking this silly question and also, I've checked in the threads related to this post still found no help. In the code snippet below:

#include <stdio.h>
main()
{
  int c;
  while((c=getchar()) != EOF)
    putchar(c); 
}

Q1: If I input hello , the output is hello . Shouldn't it just be h because although getchar can read entire string but it'll accept only one character and thus produce the output as h ?

Q2: Assume I input n , shouldn't it proceed as below:

  1. getchar function will store 'n' as a single character.
  2. Since the data type of c is an integer, the ASCII value of n is stored ie 110.
  3. This is tested against the EOF's integer value or -1 and since the result is true or Boolean has a value of 1, the body of the loop is executed.
  4. After execution of the contents in the body of loop, the control again goes back to the condition in 'while' loop and the user is prompted again to enter the character and this cycle goes on until it isn't equal to EOF ?

getchar() only consumes one character from the input stream. All of the other characters remain in the input stream for subsequent examination.

The first time you call getchar() , it returns 'h' . The second time, it returns 'e' , then 'l' , and so on. The sixth time it is invoked, it returns the end-of-line indicator '\\n' . The seventh time it is invoked, it pauses, waiting for the user to type more data.

Only when the user indicates end of file will the function return EOF. If the input is from a terminal, the user might indicate end of file by typing CTRL + D (Unix, Linux) or CTRL + Z (DOS, Windows). If the input is from a disk file, end of file is indicated after all of the file's content is exhausted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM