Multiple User Input Choices C++ - c++

I am in a beginning C++ class, and right now we are going over functions. For an assignment I have to write two functions. One should take three int arguments representing a time (hours, minutes, seconds), and return the equivalent time in seconds. The second function should take one int argument (seconds) and return the equivalent time in hours, minutes, seconds format.
I'm wondering if there is a way to give the user a choice on how many arguments to enter. For example, is there a way that I can prompt something like "Enter a time in seconds or hours, minutes, seconds form: " and if the user enters only one input call one function, but if they enter three call the other?
I realize I could give the user a choice first, such as "Enter '1' to convert from seconds to hours, minutes, seconds. Enter '2' to convert from hours, minutes, seconds to seconds." and then run a separate cin statement depending on what they choose, but is there a way to do it without this additional typing from the user?

Yes, you can do this fairly easily. Prompt the user for input. Use std::getline to read their entire input as a string. Check whether that string contains only digits (so it's one input) or has something like spaces or commas (indicating it's more than one input).
Convert the appropriate number of inputs, and call the chosen function.

There is. The simple way is to try to parse the string in two different formats. If one fails, try the other. The format that succeeded indicates which function you should call.
If you give examples of acceptable input for each function, perhaps I could offer a concrete example.

Related

C++ user input will be recorded when usleep is used, is there a way to clear them the next time cin is used to input

C++ user input will be recorded when usleep is used, is there a way to clear them the next time cin is used to input?
Many times, I want the user to see the text, I have turned off the echo so that the user can't see everything he typed, but when he next type is, everything before that will be typed, I Tried emptying the input stream, but that doesn't seem to be the problem, I'm new to c++.

How to deal with time in C++?

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

How can I create a loop that terminates at any desired year (C++)?

I was faced with creating a program that can tell a user how much interest will be added to a product after any arbitrary number of years. I had to use a loop to estimate the new price, among other things.
The problem I ran into was in the creation of the loop. I didn't know how to make it stop at any specific year that a user chose. What I did is made a for loop that outputted the loop for the next 99 years. This was my loop:
for (time>0; time<=99; time++) where time was the number of years from today.
This is obviously not ideal. I wrote this in frustration from not knowing how to create a loop that can end wherever the user wants. How can I create a loop that terminates at any desired year?
for (time>0; time<=99; time++)
This will stop at a predefined number, i.e. 99. To make it stop at a number given by user you need to:
Get the number from the user and save it in a variable
Replace 99 with the variable in your loop

Getting current date and time in C++

I am doing a school project which basically records the in and out time of an employee(of an particular company).The employee while checking in or out should enter a unique key generated specially for him so that no one else can check in and out for him.Then referring to the employees position( A worker or a manager or something like that) his total working time each day , for a week and a month is calculated. The company starts at 8 am and ends at 5 pm for 1st shift and for second shift from 3.30 pm to 2.30 am.Plus Saturday and Sunday off.
Then after a month the program refers to the working time date stored in a file and calculates his pay(For workers its per hour salary and for managers it aint). If an employee is consistently late the details are forwarded to the HR account( so that necessary steps are taken).This will help the company log the details of their employees duty time plus give enough detail to take action if someones always late.
I'm doing this as a school project and it needn't be of enterprise class and all.. But i want the coding to perform as it should.Also i'm forced to use the old Turbo C++.
Now i'm struck in the place where the time of the employees in and out time is logged.
This coding does the work
void main( )
{
clrscr();
char dateStr [9],timeStr [9];
_strdate( dateStr);
cout<<" The current date is "<<dateStr<<'\n';
_strtime( timeStr );
cout<<" The current time is "<<timeStr<<'\n';
getch();
}
I saw it somewhere on the web but can someone help me understand how it works.
I also saw another coding
typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME;
#include <Windows.h>
#include <stdio.h>
int main()
{
SYSTEMTIME st;
GetSystemTime(&st);
printf("Year:%dnMonth:%dnDate:%dnHour:%dnMin:%dnSecond:% dn"
st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
}
I think the second one is better as it not only gives me date but also gives me the day so i can check easily for the weekends.
So help me understand how these time functions work. Also if you have any suggestions for my project they are welcome.
You need to decide the format you want to store these clock "events", both for in-memory storage and manipulation and the persistent (on-disk) storage format. When you use different formats for in-memory and on-disk (or in-database) storage, you would use methods to "marshall" or "serialize"/"de-serialize" the data (look up and read about these terms). You also want to decide whether these datetime "events" will be stored or displayed in UTC (Zulu-time, GMT), or local time. You may find that storing these 'timestamps' in UTC is the best, and then you need functions/methods/routines to convert human-readable, displayable values to/from local time to UTC time.
Consider defining a "class" that has the above methods. Your class should have a method to record the current time, convert to human readable, and serialize/de-serialize the data.
Though printf works in C++, you might want to use the stream operators you have used in your first example, as they are more in the spirit of C++. Consider defining a parse method to de-serialize the data, and a to_string method (ruby uses to_s) to serialize (though reading up on stream operator overloading, and overloading the '<<' operator is more the C++ way).
The first uses C library functions (though Microsoft extensions to the standard libc). The second uses the winapi function GetSytemTime.
Both will give the system time.
The first thing I'd look at is what the rest of your code uses. You should distinguish between what is winapi code, C code and C++ code, currently your question uses a mixture of all three.
The C++ method is preferred (if you are intending to write in C++) which would be to use the newer library. The C method is as per your first example, though without mixing libc functions with stream operators (a c++ feature). The winapi method is as per your second example (I'll forgive the use of printf as FormatMessage is a pain).

How to make localized duration string?

I'm making an app in which I need to show duration string. A few examples:
1 hour 2 minutes left to break,
2 minutes 8 seconds left to break
For the moment I have a C++ function which for a given amount of seconds/milliseconds/minutes gives you a string:
wxString getTimeStr(int value,
ETimeUnit time_unit, // milliseconds or seconds or minutes or hours
wxString const & lang) // english or russian
It consists of lots of conditions depending on language, time units and existing value. Now I'm considering porting the app to other languages and it would be a bit painful to write c++ code for each new language. Is there a way to make that string using standard functions?
The app is written in C++ using wxWidgets and so far works only on Windows. I would prefer not to use platform-dependent functions, although it would be nice to know them.
You won't be able to do it perfectly without writing different code for different languages. For example, I bet your existing code doesn't allow to produce times like "5 minutes before half past threee" which are nevertheless used in (spoken) German. And even without going to such extends, consider that English "half past three" is translated to "half to four" actually.
So if using the official time is not enough (and if it is, look at wxLocale::GetInfo(wxLOCALE_TIME_FMT)), you will indeed need to write code to handle at least some languages specially.
I suggest splitting your function into two.
The first part would return the time remaining as a wxTimeSpan.
The second part 'translates' the wxTimeSpan into the required language and returns a string. This is the only part you need to change for each language.
For the sake of explanation, let's assume that
we only care about hours and minutes
Klingons like to see hours/mins
Vulcans like to see mins:hours
Russians have various forms of the word for minutes
Then your second function would be written something like this
// extract hours and residual minutes into CSV
wxString csv = theTimeSpan.Format("%H,%M);
// extract tokens for csv
wxString hours, mins
...
if( lang == "Klingon" ) {
return hours + "/" + mins
} else if ( lang == "Vulcan" ) {
return mins + ":" + hours
} else if ( lang == "Russian" ) {
wxString min_name;
switch( mins.ToLong() ) {
case 1: min_name = "---"; break;
...
}
return mins + " " + min_name;
}
Unfortunately you can NOT use Format to get an arbitrary 'time structure' because of an essential ambiguity in, for example, the number of hours in a time span. It can be either the total number of hours (for example, for a time span of 50 hours this would be 50) or just the hour part of the time span, which would be 2 in this case as 50 hours is equal to 2 days and 2 hours.
wxTimeSpan resolves this ambiguity in the following way: if there had been, indeed, the D format specified preceding the H, then it is interpreted as 2. Otherwise, it is 50. The same applies to all other format specifiers: if they follow a specifier of larger unit, only the rest part is taken, otherwise the full value is used.
So, you have to muck around with the csv tokens as shown in my code sample.
The traditional approach to the problem of localization is to build a map of label name -> label value and use place holders in the values.
In the code, you only reference the label name, and provide the values for the place holders
To port to another language, you just need to translate the map
Depending on the degree of sophistication you need, you might have a simple placeholder mechanism (snprintf-like), or one that allows a mini-language to build the value at runtime depending on simple parameters (for example, distinguishing between singular and plural).
In this example, it would be as simple as:
using LabelsType = std::map<LabelName, std::string>;
using LangToLabelsType = std::map<Language, LabelsType>;
Note: I advise an enum for the languages, rather than a plain string.
If you were on Linux I would recommend gettext, however I am unsure whether it works on Windows. Still, you can look it up and see how it works, it might help you.
Sometimes, it is better to make the program more technical rather than closer to natural language. I have also found myself in such situations (to make it looking really cool). It often was the case that the customer did not care. The information is sometimes much more important than its exact form.
A programmer should sometimes choose the tradeoffs -- a kind of meta-solution that is not related to the programming language/framework. In other words, you should weight the correctness of the solution and the correctness of the expectation.