Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've used getchar and putchar to succeessfully print my entered char to the screen before, however I've changed the code slightly and now it prints my entered char twice in a row. Code:

#include <stdio.h>

int main()
{
    int charInput;
    printf("Enter a char >> ");
    charInput = getchar();
    printf("%c", putchar(charInput));

    return 0;
}

I know I could just use putchar without the printf but I wanted to experiment with them. The output I get is:

Enter a char >> a
aa

2 chars are printed to the screen?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
460 views
Welcome To Ask or Share your Answers For Others

1 Answer

The function putchar(charInput) itself print char 'a' and return decimal equivalent of char (e.g ascii) that is printed as char using printf() so total printed two a.

Read Manual page:

int putchar(int c);

The functions, fputc(), putc(), putchar(), putc_unlocked(), and putchar_unlocked() return the character written. If an error occurs, the value EOF is returned. The putw() function returns 0 on success; EOF is returned if a write error occurs, or if an attempt is made to write a read-only stream.

So you can assume:

printf("%c", putchar(charInput));
//      ^            ^ first `a` 
//      | second `a`

is equivalent to:

temp = putchar(charInput);  // first `a`
printf("%c", temp);         // second `a`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

Just Browsing Browsing

[6] html - How to create even cell spacing within a

548k questions

547k answers

4 comments

86.3k users

...