Manumit
Manumit

Reputation: 67

How to (not) rerun c++ code?

I am doing the basic console c++ "do u want to rerun program?" dance,
and failing. This is what I'm using

int main()
{
  char repeat = 'y';        
  while (rep == 'y' || 'Y')
  {

   {
   //primary code is here
   }

  cout << "\n\tRerun program? y/n";
  cin >> repeat;
  if (rep == 'n' || 'N')
  {cout << "\n\tExiting program\n";}
  }

return 0;
}

When my program finishes, it restarts and outputs "Exiting program"
no matter what I input at "Rerun program?"I understand this has
something to do with flushing or resetting the char "repeat"?
No idea how to do that and google isn't helping.

I can submit the primary program code on request, but I doubt it has
anything to do with this error.

Upvotes: 3

Views: 118

Answers (1)

AlbertFG
AlbertFG

Reputation: 157

if (rep == 'n' || 'N') will be always true, because it actually doing if( (rep =='n') or 'N') ('N' has nonzero value which mean the if-statement is doing : if( (rep =='n') or true) ), so you always got "Exiting program" printed.

you should you if (rep == 'n' || rep =='N')

and the same, your while statement should be while (rep == 'y' || rep == 'Y')

OR

move the

cout << "\n\tExiting program\n";

out your while loop without condition to get it printed only when finish the loop

Upvotes: 3

Related Questions