Basically I need to write a program that will ask the user to enter arrival and departure time in the 24 hour format and it needs to calculate the difference between them. I know how to do everything else, but i'm not sure how to make it so that it lets you enter the time.
Asked
Active
Viewed 125 times
-1
-
Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Oct 18 '21 at 09:08
-
As a new user here, also take the [tour] and read [ask]. Doing a bit of online research, what resources have you found for C++ time handling? Just to make it clear, just asking a very basic question that doesn't indicate any research at all is just going to get you downvoted and the question closed here. Put some effort into solving the problem yourself first, only then you are really welcome to ask here! – Ulrich Eckhardt Oct 18 '21 at 09:11
-
Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please learn how to [edit] your question to improve it, file for example showing us a [mre] of your own attempt together with a description of the problems you have with it. – Some programmer dude Oct 18 '21 at 09:11
-
@vll, C++ definitely has utilities for parsing times. – chris Oct 18 '21 at 09:14
-
2For anything regarding time : use https://en.cppreference.com/w/cpp/chrono. It will prevent you from creating a lot of bugs with time boundaries (day boundaries, leap years etc). @vII C++20 has support for that : https://en.cppreference.com/w/cpp/chrono/parse – Pepijn Kramer Oct 18 '21 at 09:22
2 Answers
1
You can use std::get_time
to parse the input into a std::tm
structure. You can use std::chrono::system_clock::from_time_t
to convert the std::tm
object into a time point. You can subtract the time points to calculate the difference.
In C++20, you may streamline the code using std::chrono::parse
.

eerorika
- 232,697
- 12
- 197
- 326
-1
- Validate your input with a regex like this regex time.
- Use Posix time to create arrival and departure objects.
- Use
diffTime
to get the difference. Example here

Ionut Alexandru
- 680
- 5
- 17