2017-08-10 20 views
-2

我的程序要求用戶反覆輸入非負數條目(否定退出),直到它們給出負數退出或數組填滿爲止。我按順序返回數字而不重複。唯一的問題是我不知道怎麼我的環路內實現負進入條件:如何實現負面用戶條目以退出程序和打印列表?

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

回答

0

你在找這個?

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

表示結束的代碼,我還需要打印的清單。我將我的主分割成兩個函數,我稱之爲getInput和printList。 –

+1

這將結束程序,而不是輸入。改用'break'。 –

+0

printList應該在while循環之後。不在裏面。它不會結束程序 –

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"