繁体   English   中英

为什么下面的代码不断打印 value10?

[英]why the below code keep printing the value10?

我打算做一个循环,如果我输入字母,那么 ascii 值就会出现。 除非我输入“0”。

但结果如下。 结果下面是我制作的代码。 值 10 来自哪里?

按任意字母 A 65 按任意字母 10 按任意字母

char aski;
while(1) 
{
    printf("Press any Alphabet\n");
    scanf("%c", &aski);
    if (aski == '0') 
        break;
    else
        printf("%d\n", aski);
}

scanf读取额外的\\n \\n ASCII 是 10。这就是你得到 10 的原因。我建议你使用getchar()来读取额外的\\n

#include <stdio.h>
int main()
{
    char aski;
    while (1)
    {
        printf("Press any Alphabet\n");
        scanf("%c", &aski);
        getchar();
        if (aski == '0')
            break;
        else
            printf("%d\n", aski);
    }

    return 0;
}

输出是:

Press any Alphabet
a
97
Press any Alphabet
b
98

PS:进入b后,我停止执行。

当您按下 Enter 键时,您实际上是在创建一个 \\n(新行)该字符的值为 10,即正在打印的值。

char c = '\n';
printf("%d",c);

结果会给你10。

尝试这个

char aski;
scanf("%c ", &aski);

注意 %c 后面的空格,这确保读取所有输入的空格。

暂无
暂无

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

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