Hello!
I had a task - The program requests time in the format hh: mm: ss and checks the correctness of the input.
I have created the code, but entering the example 22:22:22 shows that it is not correct, but it should show that the time is correct. Need some more testing or how to fix this?
#include <iostream>
#include <string>
#include <sstream>
constexprchar delim {':'};
bool timeCheck(int st, int min, int sec) {
return (((st >= 0) && (st < 24)) && ((min >= 0) && (min < 60)) && ((sec >= 0) && (sec < 60)));
}
int main() {
for (std::string in; (std::cout << "Input time format - HH:MM:SS (<CR> to end): ") && std::getline(std::cin, in) && !in.empty(); ) {
std::istringstream ss(in);
char c1, c2;
int st, min, sec;
if ((ss >> st >> c1 >> min >> c2 >> sec) && (c1 == delim) && (c1 == c2) && timeCheck(st, min, sec))
std::cout << "Time format is valid\n";
else
std::cout << "Time format is not valid\n";
}
}
Input time format - HH:MM:SS (<CR> to end): 22:22:22
Time format is valid
Input time format - HH:MM:SS (<CR> to end):
@coder777 >> stops extracting a number when at least one digit has been extracted and leaves the first non-digit in the stream ready for extraction and doesn't fail the stream in this case. Only if no digits can be extracted when reading a number does extraction fail the stream. When extracting from a stream, white-space is taken to be an extraction-stopping delimiter - as well as after a non-digit for a number where at least one digit has been extracted successfully.