-1

I wrote a program to read from input character by character and print it to output and here is my code:

#include <stdio.h>

main()
{

    int c;
    while((c = getchar()) != EOF)
    {
        printf("%s\n", "log1");
        printf("%c\n", c);
        printf("%s\n", "log2");
    }

}

and this is the result:

a(my input)
log1
a
log2
log1


log2

but it should have this result:

a
log1
a
log2

what's wrong with this program?

Pooya
  • 992
  • 2
  • 10
  • 31

5 Answers5

2

you giving input a and newline

a(my input)  You are giving a and newline

//this is because of a 
log1
a
log2 

//this is because of newline
log1


log2

Check for newline and avoid printing Newline.

    while((c = getchar()) != EOF)
        {
            if(c!='\n')
               {  
                printf("%s\n", "log1");
                printf("%c\n", c);
                printf("%s\n", "log2");
               }
        }
Gangadhar
  • 10,248
  • 3
  • 31
  • 50
0

This is because you while((c = getchar()) != EOF) ends after hitting EOF. This is because when you type something and you hit the enter key then everything is stored in an internal buffer.

Your code stops when getchar doesn't find anything in that buffer.

You may also check out this:- Where does getchar() store the user input?

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

getchar is running during the second iteration. The problem is that your input was actually "a[enter]", so the second character that getchar read was a newline character, and it printed that.

If you give input of "abc", the things may seem more clear.

sasmith
  • 415
  • 4
  • 9
0

while(getchar() != '\n');

bear in mind that the expression in the while loop is executed everytime - so even when the character is '\n' is found, it has already been removed from the stream by the getchar() call.

CodeMonk
  • 920
  • 1
  • 12
  • 22
0

Place a condition not to print \n (on pressing Enter

  while((c = getchar()) != EOF)
        {
            if(c != '\n') 
            printf("%s\n", "log1");
            printf("%c\n", c);
            printf("%s\n", "log2");
        }
haccks
  • 104,019
  • 25
  • 176
  • 264