简体   繁体   中英

Multiple User Input Choices 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM