Why does getchar () behave differently?

I found that it getchar()behaves differently in some situations.
In the following code, it devours a newline at the input.

#include <stdio.h>

// copy input to output; 1st version
int main()
{
    int c;

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

The inputs and outputs in the terminal are as follows.

j
j
b
b
asdf
asdf
ashdfn
ashdfn

It accurately duplicates the input and ignores the newline character at the input due to the keystroke I after each input.

However, if there is an operator in the loop printf(), it no longer ignores the newline character.

#include <stdio.h>

// copy input to output; 1st version
int main()
{
    int c;

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

The inputs and outputs in the terminal are as follows.

j
j


b
b


asdf
a
s
d
f


ashdfn
a
s
h
d
f
n

It repeats the newline character that was used to ignore in the previous situation.

Could you tell me why there is a difference and how it behaves exactly?

+1
source share
5 answers

- getchar() - putchar(), '\n'. - .

printf("\n"), - putchar().

+2

getchar . 123 Enter, C \n ( Enter). getchar , getchar.
, , ;

#include <stdio.h>

int main(void)
{
     int c, b;

     c = getchar();
     putchar(c);

     b = getchar();
     putchar(b);

     b = getchar();
     putchar(b);
 }  

123,

123\n

char s; '1', '2', '3' '\n'.
getchar 1, putchar . 23\n. getchar 2, 3. , \n getchar. ,

123

, . j j\n . getchar j putchar . \n putchar , . getchar, b , . - \n, getchar. \n getchar.

#include <stdio.h>

// copy input to output; 1st version
int main()
{
    int c;

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

, .

#include <stdio.h>

// copy input to output; 1st version
int main()
{
    int c;

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

, , ?

, ! , j, b... .., \n. j\n, b\n.
getchar, j printf, \n ,

j
    //The newline printed by printf along with j    
    //The newline printed by printf along with \n 
b   
+1

. getchar() - . , getchar() -. , Enter .

abcde Enter

getchar() -, char , newline, char . putchar() char . Enter.

, - printf.

0

http://ideone.com/H2kqBq

#include <stdio.h>
int main()
{
int c;

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

, .

getchar() putchar()

0

, , , 'a', Enter, two characters

'a' and '\n'

therefore, loopexecuted twice before putchar these two characters, so your next input starts on a new line

(you can check this using:

if(c!='\n') putchar(c);

this will cause '\ n' to not be printed and you will enter it on the same line)

when you add printf("\n"), it will also be printed twice because the loop will be executed twice since there are two characters in the input stream.

so you get

a
(newline from printf)

in first iterationcycle

(newline from input buffer)
(newline from printf)

in second iteration

0
source

All Articles