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

在使用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

posted on 2015-10-20 15:55  C Pointer  阅读(1458)  评论(0编辑  收藏  举报

导航