-2

My goal is to create a C++ program that executes a chunk of code repeatedly until the user enters in an appropriate value and does so with the use of a while loop. My code is just repeating over and over and even if I input a "0" it still repeats the chunk of code in the loop.

Here is my source code:

#include <iostream>
using namespace std;

int main()
{
    int num = 0;
    bool repeat = true;
    while (repeat = true)
    {
        cout << "Please select an option." << endl;
        cout << "[1] Continue Program" << endl;
        cout << "[0] Terminate Program" << endl;
        cout << "---------------------" << endl;

        repeat = false;

        cin >> num;
        cout << endl;

        if (num = 1)
        {
            repeat = true;
            //execute program
        }
        else if (num = 0)
            repeat = false;
        else
            cout << "Please enter an appropriate value.";
    }

    return 0;

}

3 Answers3

2
  while (repeat = true)
                ^^

is one of your problems:

  while (repeat == true)
                ^^

With an assignment, the condition always evaluates to a true.

Some people advocate using Yoda condition to avoid these typos. Another way is to simply compile your program with the highest warning levels:

-Wall
Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
2

Check your operators. You're using the assignment operator = instead of the comparison operator == in your while and if arguments.

cognoscente
  • 88
  • 1
  • 8
1
while (repeat = true)

In the while condition, you are using the assignment operator =, not equality ==.

It's valid C++ syntax, but not what you expected. repeat is assigned to true, so the condition is always true.

The same error exists in if (num = 1) and else if (num = 0).

Yu Hao
  • 119,891
  • 44
  • 235
  • 294