如何实现否定用户输入退出程序和打印列表?
How to implement negative user entry to quit program and print list?
我的程序反复要求用户输入非负条目(负值退出(,直到他们给出负值退出或填充数组。我按顺序返回数字,不重复。唯一的问题是我不知道如何在循环中实现负输入条件:
int main(){
int arr[ARR_SIZE];
int number, arrIndex = 0;
//gets input
for (int i = 0; i < ARR_SIZE; i++){
cout << "Enter a number (negative to quit): ";
cin >> number;
if ((!ifExists(arr, 10, number)))
{
arr[arrIndex++] = number;
}
}
for (int i = 0; i < arrIndex; i++) //prints array
{
std::cout << arr[i];
}
return 0; }
您可以使用break
在特定点退出循环:
for (int i = 0; i < ARR_SIZE; i++){
cout << "Enter a number (negative to quit): ";
cin >> number;
if (number < 0)
break; // exits the for-loop at this point and continues after the loop.
if ((!ifExists(arr, 10, number)))
{
arr[arrIndex++] = number;
}
}
//... program will continue here after a certain "break"
你在找这个吗??
if (number<0)
return 0;
编辑:如果要继续程序执行,请使用break
而不是return 0
您可能还希望将 for 循环中的条件更改为arrIndex<ARR_SIZE
而不是i < ARR_SIZE;
而且您不需要变量i
,所以我建议使用while
循环。在我看来,这样会更具可读性。
while( arrIndex< ARR_SIZE){
cout << "Enter a number (negative to quit): ";
cin >> number;
if (number<0)
break;
if ((!ifExists(arr, 10, number)))
{
arr[arrIndex++] = number;
}
}
相关文章:
- 为什么异常不退出程序?
- LLVM | codegen 用于带有命令行选项的程序输入功能
- 虽然循环在使用回车键时不退出程序
- 如果 I/O read() 处于阻塞阶段,如何使用 Ctrl+C 退出 C++ 程序?
- 程序输入名称和高度并显示它。我不知道如何显示列表中最高人的姓名和身高
- 捕获异常后如何退出程序执行
- 在C++中使用exit()退出程序有问题吗
- 从函数打印 CLI 帮助消息后,我应该如何干净地退出 C++ 程序?
- 如何实现否定用户输入退出程序和打印列表?
- gdb 退出:程序接收信号 SIGILL,使用 gcc / intel_mkl / gfortran -mavx 编译的
- 程序输入密码并解锁窗口7,8,10
- 试图调节我的 do-while 以停止在终端中退出程序.菜单不会根据需要循环使用当前语句
- 我想让程序保持运行,直到用户输入 n 退出程序
- 我找不到第一个用户输入后立即退出程序的原因
- 为什么当我尝试输入"x"退出程序时出现分段错误
- 错误的输入将退出程序c++
- 在输入值后跳过一些代码并退出程序
- 当用户输入一个特殊字符时如何退出程序
- 如何在没有输入的情况下退出c++程序
- 在c++中使用函数中的用户输入退出程序