如何实现否定用户输入退出程序和打印列表?

How to implement negative user entry to quit program and print list?

本文关键字:退出程序 输入 打印 列表 用户 何实现 实现      更新时间:2023-10-16

我的程序反复要求用户输入非负条目(负值退出(,直到他们给出负值退出或填充数组。我按顺序返回数字,不重复。唯一的问题是我不知道如何在循环中实现负输入条件:

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;
}   
}