bAsH bAsH - 25 days ago 16
C Question

Why does type int work with sscanf but int16_t doesn't?

I'm trying to assign values from user input stream to variables M and N. I can get my code to work if I specify M and N of type int. However, when i specify them as int16_t using the stdint.h it will read the first value in but the last value it won't. Why is this?

Here the code is working just fine...

#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;
}


Here it does not work.

#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;
}

Answer

You're using the wrong specifier for the type int16_t, and thus the behavior is undefined.

The correct specifier for int16_t when used in scanf is SCNd16:

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

And the specifier for printf is PRId16. Its usage is the same.

Comments