Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an if condition return if its true or while return if its true

Tags:

c++

When the condition is true or false, how can I make it return back and ask the question again, making the user re-enter the value? Here is what I want to implement:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    int n;
    cout<<"Enter numbers. Press 5 to stop: ";
    cin>>n;
    bool tr=true;
    while(tr)
    {
        if(n!=5)
            cout<<"You entered "<<n; //How to make it return again, since its false? I keep getting infinite loops :( ;
        else 
            tr=false;
    }
    return 0;
}

1 Answers

You need to prompt the user in the while loop, so that it occurs in each iteration:

int n;
bool tr = true;
while(tr)
{
  cout << "Enter numbers. Press 5 to stop: ";
  cin >> n;
  if(n!=5) {
    cout << "You entered " << n;
  } else {
    tr = false;
  }
}
like image 135
Joseph Mansfield Avatar answered Dec 13 '25 22:12

Joseph Mansfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!