Ian
Ian

Reputation: 25

Separating user input of time in C++

I need to take a users input such as 10:35 and put it into a variable of hours and minutes. How can I do this using the colon as the separate for the two? This is how the assignment requires it be entered.

Example of what I am doing.

int main()
{
    char again = 'y';
    int userHours = 0;
    int userMinutes = 0;

    while (again == 'y')
    {
        cout << "Enter a time in 24-hour notation: ";
        cin >> userHours >> ":" >> userMinutes;
    }
    return 0;
} 

Upvotes: 0

Views: 2731

Answers (3)

Borgleader
Borgleader

Reputation: 15916

You almost had it:

#include <iostream>

int main()
{
    int hours, minutes;
    char colon;
    std::cin >> hours >> colon >> minutes;
    std::cout << hours << " : " << minutes;

    return 0;
}

Live example

Upvotes: 0

Mahdi Abdi
Mahdi Abdi

Reputation: 692

input and convert it to string , then split it into 2 strings , and then convert them in integers at last.

Upvotes: 1

Emu
Emu

Reputation: 5905

Just take the input as a string. then split the string using strtok(). insert the values into two variables. Before inserting convert the string values to integer.

Upvotes: 0

Related Questions