您的位置:首页 > 编程语言 > C语言/C++

C语言中固定大小的数据类型的输入和输出

2015-10-20 15:55 489 查看
在使用C语言时,对数据的大小要求比较严格时,例如要使用32位的整数类型,这时要使用 int32_t,无论平台如何变化,数据大小仍然是32位,固定位数的数据类型还有 uint32_t、uint64_t 等等。

当要输入输出这些数据时,格式字符串该如何写?C标准库提供了一系列的macro方面构造格式字符串,这些定义于头文件 <
inttypes.h>。


对文件中内容摘了了一段wiki的介绍

Printf format string
The macros are in the format PRI{fmt}{type}.
Here {fmt} defines the output formatting and is one of d (decimal), x (hexadecimal), o (octal), u (unsigned) and i (integer).
{type} defines the type of the argument and is one of N, FASTN, LEASTN, PTR, MAX, where N corresponds to the number of bits in the argument.

Scanf format string
The macros are in the format SCN{fmt}{type}.
Here {fmt} defines the output formatting and is one of d (decimal), x (hexadecimal), o (octal), u (unsigned) and i (integer).
{type} defines the type of the argument and is one of N, FASTN, LEASTN, PTR, MAX, where N corresponds to the number of bits in the argument.


打开头文件 <inttypes.h> 可以看到这些具体是什么



很清楚看到只是些printf格式字符串的数据类型替代符,系统已经帮我们定义好了,使用起来也很方便,直接套用就行了。

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main()
{
int32_t num = 0;

printf("Input a number: ");
scanf("%"SCNd32, &num);
printf("The input number is: %"PRId32"\n", num);
return 0;
}


想看详细的介绍,可以参考wiki的文档: C data types
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: