Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sscanf seems to behave different on uint variables vs int variables in c [duplicate]

Tags:

c

int

scanf

uint

I am developing a microcontroller program and want to read digits from a string into integer variables using sscanf(). The problem is I get a different behavior when using int declarations vs uint8_t or uint16_t.

This is using int for variable declaration:

 #include <stdio.h>
 #include <stdint.h>
 int main()
 {
     int power;
     int hr;
     int cadence;
     sscanf("204 67 94","%d %d %d",&power, &hr, &cadence);
     printf("power: %d, hr: %d, cadence: %d", power, hr, cadence);        
     return 0;
 }

and when put into https://www.onlinegdb.com/ returns:

power: 204, hr: 67, cadence: 94

...Program finished with exit code 0
Press ENTER to exit console.

This is the way I would expect it to behave.


Whereas using uint8_t and uint16_t integers:

#include <stdio.h>
#include <stdint.h>
int main()
{
    uint16_t power;
    uint8_t hr;
    uint16_t cadence;
    sscanf("204 67 94","%d %d %d",&power, &hr, &cadence);
    printf("power: %d, hr: %d, cadence: %d", power, hr, cadence);
    return 0;
}

when put into https://www.onlinegdb.com/ delivers an output of:

power: 0, hr: 67, cadence: 94

...Program finished with exit code 0
 Press ENTER to exit console.

So for some reason power (or more general it seems the first variable) is set to 0. Could anybody please point me in the right direction and explain what I am doing wrong?

like image 740
vbretsch Avatar asked Dec 23 '22 10:12

vbretsch


1 Answers

In the second example, you're using the wrong formats for the types of the variables.

You should use the macros from <inttypes.h>:

 SCNu8   --> uint8_t
 SCNu16  --> uint16_t

You would probably be safe with %hhu for the uint8_t and %hu for the uint16_t.

You get odd behaviour because you lied to your compiler; this is how it gets its own back. Don't lie to your compiler!

like image 102
Jonathan Leffler Avatar answered Apr 28 '23 07:04

Jonathan Leffler