Need help to stop program terminating without user

2019-07-17 04:49发布

The following code is supposed to do as follows:

  1. create list specified by the user

  2. ask user to input number

3.a) if number is on the list , display number * 2, go back to step 2

3.b) if number isn't on the list, terminate program

HOWEVER step 3.a) will also terminate the program, which is defeating the purpose of the while loop.

here is the code :

#include <iostream>
#include <array>
using namespace std;
int main()
{
cout << "First we will make a list" << endl;

array <int, 5>list;
int x, number;
bool isinlist = true;

cout << "Enter list of 5 numbers." << endl;

for (x = 0; x <= 4; x++)
{
    cin >> list[x];
}
while (isinlist == true)
{
    cout << "now enter a number on the list to double" << endl;
    cin >> number;

    for (x = 0; x <= 4; x++)
    {
        if (number == list[x])
        {
            cout << "The number is in the list. Double " << number << " is " << number * 2 << endl;
        }
        else
            isinlist = false;
    }
}
return 0;
}

Please can someone help me to resolve this ?

2条回答
看我几分像从前
2楼-- · 2019-07-17 05:00

Your issue is that you set isinlist to false as soon as one single value in the list is not equal to the user input.

You should set isinlist to false ay the beginning of your while loop and change it to true if you find a match.

Stepping your code with a debugger should help you understand the issue. I encourage you to try it.

查看更多
Emotional °昔
3楼-- · 2019-07-17 05:13

I would suggest that you encapsulate the functionality of step 3 into a separate function. You could define a function as follows, and then call it at an appropriate location in the main function.

void CheckVector(vector<int> yourlist)
{
  .... // Take user input for number to search for
  .... // The logic of searching for number. 
  if (number exists)
  {
    // cout twice the number
    // return CheckVector(yourlist)
  }
  else
    return;
}

The same functionality can be implemented with a goto statement, avoiding the need for a function. However, using goto is considered bad practice and I won't recommend it.

查看更多
登录 后发表回答