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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With