简体   繁体   中英

While loop or function for input validation

I was assigned to write a program in C++ to take user input, perform some calculation, then present the user with the information after calculations were performed.

The specifics of the program are not needed, since my question is in reference to input validation specifically. What is considered to be better practice / more practical for validating multiple user inputs?

  1. Using a while loop in int main() to catch bad input after every cin statement

OR

  1. Passing input to a function with 1 while loop to validate the input, the return the input back.

I am fairly new to programming in general, and have only been working in C++ for a few weeks, and my greenhorn instincts would tell me to create a few while loops in int main() and call it a day. Something tells me a function would be a better idea, because, you know, object orientation.

Thanks in advance. - Wes

You're correct in that you should put it into a function, encapsulation is always easier in the long run (even if you're never gonna look at this program again), and it's useful to keep good practice no matter the project!

If you're not intending on making any changes to the input and it's a case of valid input or invalid input, then you could always return a bool so you could do something like

if(inputValidator() == true)
{
    //perform calculations
}
else 
{
    //Tell the user their input is incorrect and prompt for the input again
}

Making a function to validate an input is an interesting way to solve the problem. But I doubt that it will not be necessary at the level you are coding - since you said you are a beginner programmer. If you are only checking one input at a time the best way to go will be just a simple while if you are checking multiple looks you can use something similar to while but use a for loop to go through all the entries. Best of luck to you!

In the scope which you described, it is usually not necessary to create a function, as you can just clump everything into int main and not have much issue.

However, if your list is a variable size, you could use a for loop based on the number of inputs you receive, and create an exception checker for them. Such as:

string myOutput;
for (int i = 0; i < totalInputs; i++) {
    cin << myInput;
    myOutput = exeptionHandle(myInput);
    cout << myOutput;
}

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