Check input time format

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>

using namespace std;

const char delim = ':';

bool timeCheck(int st, int min, int sec) {
return (((st >= 0) && (st < 24)) && ((min >= 0) && (min < 60)) && ((sec >= 0) && (sec < 60)));
}

int main() {
string in;
stringstream ss;
char c1, c2;
int st, min, sec;

cout << "Input time format - HH:MM:SS" << endl;
while (true) {
getline(cin,in);
ss.str(in);
if ((ss >> st >> c1 >> min >> c2 >> sec) && (c1 == delim) && (c1 == c2) && timeCheck(st, min, sec)) {
cout << "Time format is valid" << endl;
} else {
cout << "Time format is not valid" << endl;
}
}
return 0;
}
Last edited on
The problem is that >> expects a white space as a delimiter which is not the case here.

Consider to use std::getline(..., ':'); instead.
In which line u mean to do that ?
This works with VS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <sstream>

constexpr char 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.

Last edited on
Topic archived. No new replies allowed.