2012-10-29 29 views
2

我的項目是讓用戶輸入5000個數字到數組中,但允許他們隨時停止。我大部分的代碼都被關閉了,但是當用戶輸入「-1」然後顯示數組時,我無法知道如何停止所有的事情。這是我到目前爲止的代碼:當用戶輸入「-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 
+0

您不能「停止」數組。 – paddy

回答

2

在第一for循環,添加一個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 < 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 
+0

我不確定C語言中的編程約定,但如果你不想使用'break',你可以檢查輸入是否是循環的另一個條件。 –

+0

我沒跟着。所以我會在循環之後放置一個if語句?它不會在第一次休息之後停止並且不顯示任何東西嗎? –

+0

'break'隻影響它所在的​​循環。第一個循環的'if'語句使程序停止在-1處請求用戶輸入。第二個循環的「if」語句使得程序只打印數組中的東西,直到輸入停止點。 –

相關問題