bAs*_*AsH 1 c scanf fgets 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;
}
Run Code Online (Sandbox Code Playgroud)
在这里它不起作用.
#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;
}
Run Code Online (Sandbox Code Playgroud)
您对int16_t类型使用了错误的说明符,因此行为未定义.
在scanf中使用时,int16_t的正确说明符是SCNd16:
sscanf(str, "%"SCNd16" %"SCNd16, &M, &N);
Run Code Online (Sandbox Code Playgroud)
printf的说明符是PRId16.它的用法是一样的.