C 让数组在用户输入时停止"-1“;

C 让数组在用户输入时停止"-1“;,c,C,我的项目是,我必须让用户在数组中输入5000个数字,但允许他们随时停止。我已经记下了大部分代码,但我不知道如何在用户输入“-1”然后显示数组时停止所有操作。以下是我目前的代码: #include <stdio.h> #include<stdlib.h> #define pause system("pause") #define cls system("cls") #define SIZE 50 int i; main() { int i; int userInpu

我的项目是,我必须让用户在数组中输入5000个数字,但允许他们随时停止。我已经记下了大部分代码,但我不知道如何在用户输入“-1”然后显示数组时停止所有操作。以下是我目前的代码:

#include <stdio.h>
#include<stdlib.h>
#define pause system("pause")
#define cls system("cls")
#define SIZE 50
int i;


main() 
{

int i;
int userInput[SIZE];

for (i = 0; i < SIZE; i++) 
{
    printf("Enter a value for the array (-1 to quit): ");
    scanf("%i", &userInput[i]);

} // end for

for (i = 0; i < SIZE; i++) 
{
    if (userInput[i] == -1) 
    printf("%i. %i\n", i + 1, userInput[i]);
    pause;
} // end for


pause;
  } // end of main 
#包括
#包括
#定义暂停系统(“暂停”)
#定义cls系统(“cls”)
#定义尺寸50
int i;
main()
{
int i;
int userInput[SIZE];
对于(i=0;i
在循环的第一个
中,添加一个if语句来检查输入,如果输入是
-1
,则中断循环

 for (i = 0; i < SIZE; i++) {
    printf("Enter a value for the array (-1 to quit): ");
    scanf("%i", &userInput[i]);
    if(userInput[i] == -1){
      break; //break the for loop and no more inputs
    }
  } // end for
for(i=0;i
此外,我认为您希望显示用户输入的所有数字。如果是,则第二个循环应如下所示:

for (i = 0; i < SIZE; i++) {
   printf("%i. %i\n", i + 1, userInput[i]);
   if (userInput[i] == -1) {
      break; //break the for loop and no more outputs
   }
 } // end for
for(i=0;i
我不确定C语言中的编程约定,但如果您不想使用
中断
,可以将输入作为循环的另一个条件进行检查。我不遵循。所以我会在这两个for循环后面加一个if语句?它会不会在第一次中断后停止,不显示任何内容?
break
只会影响它所在的循环。第一个循环的
if
语句使程序停止在-1请求用户输入。第二个循环的
if
语句使程序只打印数组中的内容,直到输入停止。@MatthewYoung:
break
语句只中断当前循环。因此,只要用户输入
-1
,您的第一个for循环就会停止。现在,控件将移出
for
循环,并继续执行下一条语句。由于已将
-1
存储在数组中,因此第二个for循环将在到达该索引时中断。我相信这就是你想要的。非常感谢!!我终于成功了。我总是来这个网站查看别人的代码,但我从来没有想过要发布我自己的问题。看来我以后会在这里发布更多。。。再次感谢!!