-1

I have been experimenting with getchar(), putchar() and have been trying to use EOF. Below is the snippet of code I have been experimenting with.

#include <stdio.h>

int main(void)
{
    int c;
    c = getchar();

    while(c != EOF)
    {
        putchar(c);
        printf("\n");
        printf("%d\n", EOF);
        c = getchar();
    }

    return 0;
}

Input: -

a

Expected output: -

a //Due to putchar()

-1 //Value of EOF

//Now the cursor should come in next line and wait for next character.

Output getting in real time: -

a

-1

-1

//Cursor waiting for next character.

I am not able to comprehend the reason why the output is showing -1 two times.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Swarnim Khosla
  • 117
  • 1
  • 10
  • If you remove the EOF printing will it still show that one -1? And is it printing another newline between the -1s? – Maxxik CZ Dec 03 '19 at 14:45
  • 2
    `//Now the cursor should come in next line and wait for next character.` The second loop *doesn't wait* but reads a newline. Did you notice the extra blank line in the output? – Weather Vane Dec 03 '19 at 14:46
  • @MaxxikCZ No it will not show `-1`, but it will then have two more `\n` in output stream. – Swarnim Khosla Dec 03 '19 at 14:47
  • @WeatherVane Thank you.Please point out the fact in form of an answer, I shall accept your answer. – Swarnim Khosla Dec 03 '19 at 14:50

2 Answers2

1

Your code comment says

//Now the cursor should come in next line and wait for next character.

But the second loop doesn't wait. It reads the newline that was already entered, and this is shown by the extra blank line in the output.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
1

After the first input before the loop

c = getchar();

the input buffer contains the new line character '\n' that corresponds to the pressed key Enter.

So in the while loop there are outputted

a

and

-1

due to the statement

printf("%d\n", EOF);

After that this statement in the loop

c = getchar();

reads the new line character that is present in the input buffer. So again this statement

printf("%d\n", EOF);

outputs

-1
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335