Scanf cannot scan in uint8_t

When I try to use scanfwith uint8_t, I get crazy results. Using int, I get the expected output of "08 - 15". Using uint8_t, I get "00 - 15".

const char *foo = "0815";
uint8_t d1, d2; // output: 00 - 15 (!!!)
// int d1, d2;         // output: 08 - 15
sscanf(foo, "%2d %2d", &d1, &d2);
printf("%02d - %02d\n", d1, d2);

I am using GCC.

+1
source share
4 answers

%dincorrect because it means that you are passing int *, but you really want to pass uint8_t *. You will need to use the appropriate macro:

#include <inttypes.h>
...
sscanf(foo, "%2" SCNu8 " %2" SCNu8, &d1, &d2);

Most compilers should give you warnings about your version of the code. Here is the Clang output:

test2.c: 8: 24: warning: format specifies type 'int *' but the argument has type
      'uint8_t *' (aka 'unsigned char *') [-Wformat]
sscanf(foo, "%2d %2d", &d1, &d2);
             ~~~       ^~~
             %2s
test2.c:8:29: warning: format specifies type 'int *' but the argument has type
      'uint8_t *' (aka 'unsigned char *') [-Wformat]
sscanf(foo, "%2d %2d", &d1, &d2);
                 ~~~        ^~~
                 %2s
2 warnings generated.

uint8_t printf(), uint8_t int printf().

+7

scanf %d : " int *". , int. . ( undefined.)

: .

+3

, scanf(), 4 (int), uint8_t - .

0
#define __USE_MINGW_ANSI_STDIO 1 //or gcc prog.c -std=c99 -D__USE_MINGW_ANSI_STDIO

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main(){
    const char *foo = "0815";
    uint8_t d1, d2;
    sscanf(foo, "%2" SCNu8 "%2" SCNu8, &d1, &d2);
    printf("%02" PRIu8 " - %02" PRIu8 "\n", d1, d2);
    return 0;
}
0
source

Source: https://habr.com/ru/post/1692483/


All Articles