I have been trying to extract hours, seconds and minutes from an input text using sscanf. After sscanf function is performed, only s variable which holds the seconds has the right value. h and m which have hours and minutes in them hold only zeros. Please suggest changes to my code below.
char text[20];
if (fgets(text, sizeof text, stdin)!= NULL){
char* newline = strchr(text, '\n');
if (newline != NULL){
*newline = '\0';
}
}
uint8_t s = 0;
uint8_t m = 0;
uint8_t h = 0;
sscanf(text, "%02i:%02i:%02i",&h,&m,&s);
Note in the debugger, text has the right values.
This program:
gives this output:
The
%02iconversions should also work, but the digits are somewhat superfluous.The amended question shows that the variables are of type
uint8_t, in which case you must use the correct conversion specifiers from<inttypes.h>:This produces the same output as before. With any of the
scanf()family of functions, it is crucial that your format conversion specifiers match the types of the pointers you are passing into the function. You can get away with quite a lot of mismatches inprintf()– certainly by comparison – because of default integer (in particular) promotions, butscanf()is a lot less forgiving.