为什么type int适用于sscanf但int16_t不适用?

时间:2016-11-07 18:59:51

标签: c fgets scanf stdint

我正在尝试将用户输入流的值分配给变量M和N.如果我指定类型为int的M和N,我可以使用我的代码。但是,当我使用stdint.h将它们指定为int16_t时,它将读取第一个值,但不会读取最后一个值。这是为什么?

这里的代码工作得很好......

#include <stdio.h>
#include <stdint.h>
int main(void)
{
    char str[10];
    int M, N;
    fgets(str, 10, stdin);
    sscanf(str, "%d%d", &M, &N);
    printf("M is: %d\n", M);
    printf("N is: %d\n", N);
    return 0;
}

这里不起作用。

#include <stdio.h>
#include <stdint.h>
int main(void)
{
    char str[10];
    int16_t M, N;
    fgets(str, 10, stdin);
    sscanf(str, "%d%d", &M, &N);
    printf("M is: %d\n", M);
    printf("N is: %d\n", N);
    return 0;
}

1 个答案:

答案 0 :(得分:7)

您对int16_t类型使用了错误的说明符,因此行为未定义。

在scanf中使用时,int16_t的正确说明符是SCNd16:

sscanf(str, "%"SCNd16" %"SCNd16, &M, &N);

printf的说明符是PRId16。它的用法是一样的。