Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
C++ how to take user input of time and seperate it into hours and minutes?
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;
}
Actually I already solved it thanks to the people on stackoverflow. Just need a variable for the colon, so I just added the lines.
char colon;
cin >> userHours >> colon >> userMinutes;
1 Answer
- cjaLv 77 years agoFavorite Answer
You should do something like this:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
const char delim = ':';
const unsigned hoursPerDay = 24;
const unsigned minutesPerHour = 60;
int main(int argc, char *argv[]) {
string in;
stringstream ss;
unsigned hours, minutes;
char c;
while (true) {
cout << "Enter time (HH" << delim << "MM) : ";
getline(cin,in);
ss.clear(); ss.str(in);
if ((ss >> hours >> c >> minutes) &&
(c == delim) &&
(hours < hoursPerDay) &&
(minutes < minutesPerHour)) {
cout << setw(2) << setfill('0') << hours << delim
<< setw(2) << setfill('0') << minutes << endl;
}
}
return 0;
}
#if 0
Sample run:
Enter time (HH:MM) : 13:45
13:45
Enter time (HH:MM) : 12
Enter time (HH:MM) : 9:09
09:09
#endif