需要帮助以在未经用户同意的情况下停止程序终止
Need help to stop program terminating without users consent
以下代码应执行以下操作:
-
创建用户指定的列表
-
要求用户输入号码
3.a) 如果数字在列表中,显示数字 * 2,返回步骤 2
3.b) 如果号码不在列表中,终止程序
然而,步骤3.a)也将终止程序,这违背了while循环的目的。
这是代码:
#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;
}
请有人帮我解决这个问题吗?
我建议您将步骤 3 的功能封装到一个单独的函数中。您可以按如下方式定义一个函数,然后在 main 函数中的适当位置调用它。
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;
}
可以使用 goto
语句实现相同的功能,从而避免了对函数的需求。但是,使用goto
被认为是不好的做法,我不会推荐它。
您的问题是,只要列表中的单个值不等于用户输入,您就会将 isinlist 设置为 false。
您应该在 while 循环的开头将 isinlist 设置为 false ay,如果找到匹配项,则应将其更改为 true。
使用调试器单步执行代码应有助于了解问题。我鼓励你尝试一下。
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 在未初始化映射的情况下,将值插入到映射的映射中
- 在没有程序的情况下询问用户相同的事情被终止 C++
- 为什么一个指向char的C++指针在缺少null终止符的情况下充当字符串
- C++:在没有活动异常(GCC)的情况下终止调用
- 无法在线程运行方法中运行CryptoPP FileSink的情况下终止Qt线程
- C++线程:在没有活动异常的情况下终止调用
- 需要帮助以在未经用户同意的情况下停止程序终止
- 如何在不终止主应用程序的情况下卸载 ActiveX 的 ocx 以允许覆盖 ocx?
- 如何在没有任何指示终止的输入的情况下摆脱这种"loop"?
- 如何在不终止应用程序的情况下关闭GLUT窗口
- C++:如何在没有特定"interruption points"的情况下干净地终止线程
- c++程序在不执行catch块的情况下终止
- 如何在不破坏主框架的情况下终止wxWidgets消息循环
- 在没有活动异常的情况下调用c++终止
- 在没有活动异常线程的情况下终止调用
- 如何在不终止程序的情况下停止std::线程的运行
- 可变模板类终止情况下的直接访问有效,但方便类访问无法编译
- 在不终止程序的情况下将动态分配的内存返回给操作系统