繁体   English   中英

Putchar字符出现在我的printf函数的前面

[英]Putchar character is appearing at the front of my printf function

使用此代码

void echo_char_code() {
    int x;
    printf ("Please enter a character:\n");
    x = getchar();
    printf("The character code of '%c' is %d", putchar(x), putchar(x));
    printf(". \n");
}

int main() {
    echo_char_code();
    return 0;
}

但由于某种原因,我的输出是

AAThe character code of 'A' is 65.

我想知道为什么“ AA”一开始出现,而不仅仅是我想要的“ A”和65。

您不应将putchar(x)作为参数传递,而应使用变量x。

void echo_char_code() {
    int x;
    printf ("Please enter a character:\n");
    x = getchar ();
    printf("The character code of '%c' is %d", x, x)); // changing putchar(x) to x solves the problem.
    printf (". \n");
}

int main() {
    echo_char_code();
    return 0;
}

在这条线

printf("The character code of '%c' is %d",putchar(x),putchar(x));

您两次调用putchar()两次输出x。
您还将使用这两个调用的返回值来执行格式化输出。
(如果成功的话) putchar()的返回值恰好是写入的char,这使它有些透明。
其顺序可能无法预测,但确实可以解释您观察到的结果。

比较https://en.cppreference.com/w/c/io/putchar
它指出

返回值
成功时,返回书面字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM