简体   繁体   English

如何读取 char 类型的 integer 值?

[英]How to read an integer value in char type?

I wanted to make a little experiment with scanf().我想用 scanf() 做一个小实验。 I wanted to read a small (<=255) integer from the user and store it in a char type.我想从用户那里读取一个小的 (<=255) integer 并将其存储在 char 类型中。

I did:我做了:

char ch;
scanf("%d",&ch);

It works, but I want to satisfy the compiler and not to get this warning:它有效,但我想让编译器满意而不是收到此警告:

warning: format specifies type 'int *'
but the argument has type 'char *' [-Wformat]
scanf("%d",&ch);

Any idea?任何的想法?

First of all, to store a value 0 - 255, you should never use char .首先,要存储 0 - 255 之间的值,你不应该使用char In fact you should never use char for the intention of storing anything but characters and strings.事实上,除了字符和字符串之外,你不应该使用char来存储任何东西。 This is because that type has implementation-defined signedness: Is char signed or unsigned by default?这是因为该类型具有实现定义的符号性:默认情况下 char 是有符号的还是无符号的?

You could do:你可以这样做:

unsigned char val;
scanf("%hhu", &val);

Although it is often best practice to use the portable types from stdint.h :尽管使用stdint.h中的可移植类型通常是最佳实践:

#include <stdint.h>
#include <inttypes.h>  // (actually includes stdint.h internally)

uint8_t val; 
scanf("%"SCNu8, &val);

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

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