Need help to stop program terminating without users consent

拜拜、爱过 提交于 2019-12-11 01:49:40

问题


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 ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/36111096/need-help-to-stop-program-terminating-without-users-consent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!