简体   繁体   English

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

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

I was going to make a loop that if I type the alphabet then the ascii value comes out.我打算做一个循环,如果我输入字母,那么 ascii 值就会出现。 Unless I type '0' in.除非我输入“0”。

but result is as below.但结果如下。 There is the code that I made below the result.结果下面是我制作的代码。 Where the value 10 is coming from?值 10 来自哪里?

Press any Alphabet A 65 Press any Alphabet 10 Press any Alphabet按任意字母 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 reads an extra \\n . scanf读取额外的\\n ASCII of \\n is 10. That's why you get 10. I suggest you to use getchar() to read extra \\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;
}

The output is:输出是:

Press any Alphabet
a
97
Press any Alphabet
b
98

PS: I stopped excution after, entering b. PS:进入b后,我停止执行。

When you are pressing enter you are in fact creating a \\n (new line) This char has the value of 10, which is what is being printed.当您按下 Enter 键时,您实际上是在创建一个 \\n(新行)该字符的值为 10,即正在打印的值。

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

Would give you 10 as result.结果会给你10。

Try this尝试这个

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

Notice the space after the %c, this makes sure to read all whitespace inputted.注意 %c 后面的空格,这确保读取所有输入的空格。

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

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