简体   繁体   English

%d和%c的char的scanf的不同答案

[英]different answers of scanf of a char with %d and %c

This is a program used for swapping the nibbles of a byte, which is perfect for a byte but I faced a problem. 这是一个用于交换字节半字节的程序,它非常适合一个字节,但我遇到了问题。

Code: 码:

#include<stdio.h>  

void main()
{
    unsigned char a = 0;
    scanf("%d", &a);    
    a = ((a << 4) | (a >> 4)); 
    printf("the value of a is %d\n\r", a); 
} 

You can see in the scanf statement that I've received it as %d instead of receiving it as %c which is for a char . 您可以在scanf语句中看到,我已将其作为%d接收,而不是将其作为%c接收(用于char The above code works perfectly. 上面的代码工作完美。 But if I replace %d with %c , I am getting a different undesired answer 但是,如果我将%d替换为%c ,则会得到另一个不希望的答案

Why? 为什么?

the correct specifier for scanf ing an unsigned char is %hhu , not %d . 为正确的指定符scanf荷兰国际集团的unsigned char%hhu ,不%d

So scanf("%d", &a); 所以scanf("%d", &a); should be scanf("%hhu", &a); 应该是scanf("%hhu", &a); .

You should also use int main(void) instead of void main() and remove the \\r in the printf, because \\n is a new line on every system. 您还应该使用int main(void)代替void main()并删除printf中的\\r ,因为\\n是每个系统上的新行。

In your case 就你而言

 scanf("%d", &a)

is wrong. 是错的。 %d expects a pointer to int , not a pointer to unsigned char . %d需要一个指向int的指针,而不是一个指向unsigned char的指针。 it will invoke undefined behaviour . 它将调用未定义的行为

The correct way to do it will be 正确的方法是

 scanf("%c", &a);

or 要么

scanf("%hhu", &a);

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

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