Home > Enterprise >  reprompt user input using boolean but the program doesnt validate and just exit program
reprompt user input using boolean but the program doesnt validate and just exit program

Time:11-12

I want to reprompt user after they input invalid answer. In my context, if the user enter greater than 4, it will print error and the program will reprompt it using boolan. But this is what happened:

enter image description here

It even skip the question of how many subjects the user need to input. What should I do?

Here's the code:

void Input(studentInfo &inp) {
string name;
bool year = true;
int totalSubjectSem;
cout << "\nWhat is your name: ";
cin >> inp.name;

repromptYear:
while(year) {
    cout << "What year are you in now: ";
    cin >> year;
    if (year > 4)
    {
        cout << "Your year doesn't make sense. Year couldn't exceed 4. Please enter again: ";
        year = true;
        goto repromptYear;
    }
    else
        year = false;
}

cout << "Enter how many subjects are you taking: ";
cin >> inp.totalSubjectSem;
inp.setYear(year);

}

CodePudding user response:

Without reading the details of your code, my guess is that you need to use

cout.flush();

or

cout << std::endl; // calls std::cout.flush() and prints new line.

That will take the output from couts internal buffer and put it in the actual output.

I have had the problem when the program exits and the output is not flushed to the output before the program exits.

Also like others commented: In the future, try to find other ways to controll the flow than using goto, it's considered bad practice for several reasons.

CodePudding user response:

In the comments Vlad is right. You shouldn't use bool to store number in there. It is used to store either true or false. Use int, unsigned int or short instead.

int year;
cin >> year; // Now you can get a number
  •  Tags:  
  • c
  • Related