1

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;
}
bAsH
  • 25
  • 4
  • 1
    Possible duplicate of [printf format specifiers for uint32\_t and size\_t](http://stackoverflow.com/questions/3168275/printf-format-specifiers-for-uint32-t-and-size-t) – Eli Sadoff Nov 07 '16 at 19:02
  • 1
    tl;dr you're not using the right format specifiers. – Eli Sadoff Nov 07 '16 at 19:02
  • If you think that any answer has solved your problem, please consider accepting it (the green checkmark to the left of the answer). This will indicate to the community that the question has been answered and will give some reputation to you and the answerer. – 2501 Nov 16 '16 at 10:43

1 Answers1

7

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.

2501
  • 25,460
  • 4
  • 47
  • 87