I’m writing C++ code for school in which I can only use the std library, so no boost. I need to parse a string like “14:30” and parse it into:
unsigned char hour;
unsigned char min;
We get the string as a c++ string, so no direct pointer. I tried all variations on this code:
sscanf(hour.c_str(), "%hhd[:]%hhd", &hours, &mins);
but I keep getting wrong data. What am I doing wrong.
As everyone else has mentioned, you have to use
%dformat specified (or%u). As for the alternative approaches, I am not a big fan of the “because C++ has feature XX it must be used” and oftentimes resort to C-level functions. Though I never usescanf()-like stuff as it got its own problems. That being said, here is how I would parse your string usingstrtol()with error checking:Hope it helps.