【问题标题】:extra line of output in printf statementprintf 语句中的额外输出行
【发布时间】:2012-10-16 00:59:01
【问题描述】:

我试图将一个字符作为输入,并将其 ascii 值作为输出,直到用户给出 0 作为输入。它可以工作,但总是显示一个额外的 ascii 值 10。我做错了什么?

#include <stdio.h>
#include <stdlib.h>
int main(void){
    printf("Welcome to ASCII:\n");
    char input;
    while(input != 48){
        scanf("%c", &input);
        printf("ascii: %d\n", input);
    }
    printf("done\n");

}

输出

Welcome to ASCII:
e
ascii: 101
ascii: 10
h
ascii: 104
ascii: 10
l
ascii: 108
ascii: 10
0
ascii: 48
done

【问题讨论】:

    标签: c printf output


    【解决方案1】:

    10 是 '\n' 的 ASCII 值,即按 Enter 时生成的换行符。您可以为该字符添加检查而不打印其值。

    使用'0'而不是写ASCII值48也是一种很好的风格。

    while (input != '0') {
        scanf("%c", &input);
    
        if (input != '\n') {
            printf("ascii: %d\n", input);
        }
    }
    

    【讨论】:

      【解决方案2】:

      ASCII 值 10 是new line character。你在你的角色之间打了Enter,这就是打印出来的原因。

      【讨论】:

        猜你喜欢
        • 2015-08-31
        • 1970-01-01
        • 1970-01-01
        • 2017-03-03
        • 2015-12-15
        • 1970-01-01
        • 1970-01-01
        • 2019-11-13
        • 2022-12-21
        相关资源
        最近更新 更多