1

What is the format specifier for an _int8 data type?

I am using "%hd" but it is giving me an error about stack corruption. Thanks :)

This is a snippet of the code:

signed _int8 answer;

printf("----Technology Quiz----\n\n");
printf("The IPad came out in which year?\n");
printf("Year: ");
scanf("%hd", &answer);
printf("\n\n");
printf("The answer you provided was: %hd\n\n", answer);
4

4 回答 4

5

man scanf: %hhd "... but the next pointer is a pointer to a signed char or unsigned char". An _int8 is equivalent to a signed char in any system you're going to be doing scanf on.

signed _int8 answer;
scanf("%hhd", &answer);
printf("You entered %d\n\n", answer);
于 2012-10-24T15:57:09.270 回答
3

To use the "explicit width" typedefs like int8_t and uint_fast16_t portably in C99 in the format strings of printf and scanf, you need to #include <inttypes.h> and then use the string macros PRIi8 and PRIuFAST16, like so:

#include <stdint.h>   // for the typedefs (redundant, actually)
#include <inttypes.h> // for the macros

int8_t a = 1;
uint_fast16_t b = 2;

printf("A = %" PRIi8 ", B = %" PRIuFAST16 "\n", a, b);

See the manual for a full list, and cross-reference it with the typedefs in <stdint.h>.

于 2012-10-24T16:23:24.980 回答
0

%hd will allow you to get a "short int", which is typically 16 bits, not 8 bits as might imagine. If %hhd is not supported, you may not have a good way to do this, other than scanning in as a short and assigning.

于 2012-10-24T15:59:05.513 回答
0

scanf with %hd reads a short int, which might be 16 bit on a 32 bit machine. So you are reading into answer and one byte beyond, thus the stack corruption.

Up to C90 there is no type specifier to read an 8 bit int with scanf.

%hhd is only available since C99, see also ANSI C (ISO C90): Can scanf read/accept an unsigned char?.

于 2012-10-24T16:03:17.687 回答