C++ get hour and minutes from string

c++, scanf

Solution

As everyone else has mentioned, you have to use `%d` format 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 use `scanf()`-like stuff as it got its own problems. That being said, here is how I would parse your string using `strtol()` with error checking:

#include <cstdio>
#include <cstdlib>

int main()
{
    unsigned char hour;
    unsigned char min;

    const char data[] = "12:30";
    char *ep;

    hour = (unsigned char)strtol(data, &ep, 10);
    if (!ep || *ep != ':') {
        fprintf(stderr, "cannot parse hour: '%s' - wrong format\n", data);
        return EXIT_FAILURE;
    }

    min = (unsigned char)strtol(ep+1, &ep, 10);
    if (!ep || *ep != '\0') {
        fprintf(stderr, "cannot parse minutes: '%s' - wrong format\n", data);
        return EXIT_FAILURE;
    }

    printf("Hours: %u, Minutes: %u\n", hour, min);
}

Hope it helps.

Problem

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.

Original source