Simple time program with hours and minutes

Being asked to write a program that accept both hours and minutes.

Example 2050 (24hrs format)

1) i only know how to code a program below but how to fool-prove it?? (Example a user can only input hrs from 0 to 23, minutes from 0 to 59) But how to accept both value in one input? Example 2050 << can be seperated into 20 and 50, but has to be 1 time input whereby a user cannot input 20/enter/50

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;

int main()
{
ofstream purch("PurchaseRecord.txt",ios::app);

int hour,minute;

cout << "Key in your time:";
cin  >> hour >> minute;

cout << "Your time is being saved";
purch <<"Hrs:"<<hour<<"Minutes:"<<minute;
}
The C++11 standard added a regular expressions (regex) library.
The regex library can be used for pattern matching and would be an elegant choice for your program.

Unfortunately GCC probably has yet to implement the library, but MSVC (Visual Studio) already has it, from what I remember.

http://www.cplusplus.com/reference/regex/
http://www.cplusplus.com/reference/regex/ECMAScript/
http://en.cppreference.com/w/cpp/regex

Edit: extra links.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <iomanip>

int main()
{
    int military_time ;
    std::cout << "military time? " ;
    std::cin >> military_time ;

    const int hours = military_time / 100 ;
    const int minutes = military_time % 100 ;

    if( hours >=0 && hours < 24 && minutes >= 0 && minutes < 60 )
    {
        std::cout << std::setw(4) << std::setfill('0') << military_time
                   << " is a valid military time.\n" ;
    }
}
Seeing JLBorges' example, I agree that's the natural and easy thing to do.
If however you are using Visual Studio 2013, here's the regex example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <regex>
#include <string>

void test_hour(const std::string &s)
{
	const std::regex military_hour("(([01][0-9])|(2[0-3]))(:?)[0-5][0-9]");

	if (std::regex_match(s, military_hour))
		std::cout << "Matched: " << s;
	else
		std::cout << "Did not match: " << s;

	std::cout << std::endl;
}

int main()
{
	test_hour("0000");
	test_hour("2500");
	test_hour("2459");
	test_hour("1337");
	test_hour("2359");
	test_hour("01:34");
	test_hour("23:51");
	test_hour("43");
	test_hour("Hello, World!");
	test_hour("11011");
	test_hour("-1323");
}


Matched: 0000
Did not match: 2500
Did not match: 2459
Matched: 1337
Matched: 2359
Matched: 01:34
Matched: 23:51
Did not match: 43
Did not match: Hello, World!
Did not match: 11011
Did not match: -1323


Edit:

Removed extra parentheses:

const std::regex military_hour("([01][0-9]|2[0-3]):?[0-5][0-9]");
Last edited on
Topic archived. No new replies allowed.