I am in a case when i am given two time formats hh:mm:ss to input.
I know that int
variables exctract from cin
until a non-integer is reached. This means that i can extract the hours easily, but then the character ":" would still be in the stream, which would cause a problem for the extraction of minutes.
I know i can use cin.ignore()
but since i have to input two time formats, the code just for the input would result very long and not seem too good.
Just to give you an idea:
int h,m,s, h2,m2,s2;
cin>>h;
cin.ignore();
cin>>m;
cin.ignore();
cin>>s;
cin>>h2;
cin.ignore();
cin>>m2;
cin.ignore();
cin>>s2;
I know that cin automatically ignores whitespaces. Is there a way to make it automatically ignore a specific character (in this case, the character ":")?
An easy approach is create a colon()
manipulator:
std::istream& colon(std::istream& in) {
if ((in >> std::ws).peek() == ':') {
in.ignore();
}
else {
in.setstate(std::ios_base::failbit));
}
return in;
}
You can then just extract the ':'
characters:
in >> h >> colon >> m >> colon >> s;
Obviously, I'd create an input operator for times so I could then read the two objects using
in >> time1 >> time2;
For my case also I need time input in HH:MM:SS format. I solved that ':'
input by using it as a delimiter for getline()
function. I have attached that portion of code here.
const char delim = ':';
string hr_s, min_s, sec_s;
int hr, min, sec;
cout << "Enter HH:MM:SS : " << endl;
std::getline(cin, hr_s, delim);
std::getline(cin, min_s, delim);
std::getline(cin, sec_s);
hr = stoi(hr_s);
min = stoi(min_s);
sec = stoi(sec_s);
if ((hr_s.length() == 2) && (min_s.length() == 2) && (sec_s.length() == 2)&& (isValidTime(hr, min, sec)))
{
cout << "Good Time Format" << endl;
}
else
{
cout << "Bad Time format input"<< endl;
}
The method to check the validity of the numbers input:
bool isValidTime(int hr, int min, int sec)
{return (((hr >= 0) && (hr < 24)) &&
((min >= 0) && (min < 60)) &&
((sec >= 0) && (sec< 60)));}
Note: this code has no effect unless the user input some other character instead of ':'
. For other case it should be fine. I am not sure if I answered your question or not but I hope this is helpful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.