简体   繁体   English

时间格式hh:mm:ss输入

[英]time format hh:mm:ss input

I am in a case when i am given two time formats hh:mm:ss to input. 我遇到两种时间格式hh:mm:ss输入的情况。

I know that int variables exctract from cin until a non-integer is reached. 我知道int变量从cin删除,直到达到非整数。 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. 我知道我可以使用cin.ignore()但由于我必须输入两种时间格式,因此输入的代码会导致很长时间并且看起来不太好。

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. 我知道cin会自动忽略空格。 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: 一个简单的方法是创建一个colon()操纵器:

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. 对于我的情况,我也需要以HH:MM:SS格式输入时间。 I solved that ':' input by using it as a delimiter for getline() function. 我通过使用它作为getline()函数的分隔符来解决':'输入。 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. 我不确定我是否回答了你的问题,但我希望这是有帮助的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM