Time input to int

Hello,

I just recently started taking a C++ class so I apologize if this question is too obvious for some.

I'm working on an assignment that asks to take the user input for two different times and write a function to compute the difference between the two. I'm not having an issue with the function, but with the original input.

The solution is pretty picky on the formatting it looks for, and in this scenario its asking for:
"The prompt for the start time is:
Enter start time, in the format 'HH:MM xm', where 'xm' is
either 'am' or 'pm' for AM or PM:
The prompt for the future prompt is the same with "future" replacing "start"."

How do I take an input of say, "11:39 am" and use that for 3 different variables: int hours,int minutes and bool isAM ?

Any tip or suggestion is very welcome.

Thanks!
Last edited on
You'll need to input it as a string, and then parse it. You will have to search the array to find the space and colon, and split it, then convert the strings into their types. As an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <string>
#include <iostream>

void getTime(int& minutes, int& hours, bool& isAM) {
    std::string str;
    std::getline(std::cin, str); // get the input of the time

    // find the points to split the string in
    std::size_t splitA = str.find(':');
    std::size_t splitB = str.find(' ');

    // split and convert the string as necessary
    hours = std::stoi(str.substr(0, splitA));
    minutes = std::stoi(str.substr(splitA + 1, splitB - splitA));
    isAM = ("am" == str.substr(splitB + 1));
}

// example use:
int main() {
    int minutes;
    int hours;
    bool isAM;

    getTime(minutes, hours, isAM);

    std::cout << "Minutes: " << minutes
              << "\nHours: " << hours
              << "\nIs AM: " << std::boolalpha << isAM << std::endl;

    return 0;
}


Of course, this is using the C++ std::string header, which you may or may not be using for your assignment, but you should get the overall gist.
Last edited on
Awesome, thank you.

I had a feeling it had to be done with a string, but I was not sure how to go about doing it. This also gave me a few more things to look up and read.

Thanks again.
Topic archived. No new replies allowed.