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

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

Printing a char in ANSI C

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

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

1 Answer

0 votes
by (71.8m points)

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`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...