2014-07-16 49 views
1

我想要我的數組輸入,使其不能有相同的數字兩次: 但是這將有一個輸出 「值存在,請重新輸入:」; 兩次。我如何檢查它是否是唯一的,如果它之前已經初始化,只顯示一次?如何填充不同值的數組

int main(){ 
    int arr_size = 10; 
    int value; 
    int aArray[10]; 
    for(int i=0;i<arr_size;i++) 
    { 
     cout<<"enter value of slot"<<i+1<<": "; 
     cin>>value; 

     for(int j=0;j<arr_size;j++){ 

      if(value == aArray[j]) 
      { 
      cout<<"value exist please re enter: "; 
      cin>>value; 
      } 
      else{ 

      aArray[i] = value; 
      } 
     } 
    } 

    } 
+3

使用['性病::設置'](http://en.cppreference.com/mwiki/index .php?title = Special%3ASearch&search = std%3A%3Aset)而不是原始整數數組。 –

+0

你可能會考慮插入一個'std :: set'並檢查結果。即使是最小的變化,使用'std :: find'代替循環。另外請注意,如果在目前設置的元素中找不到元素,您正在讀取未初始化的數據。 – chris

+0

或者您只需在數值再次輸入後引入'break'。但是你不會初始化你的錯誤,因此你的* exists *檢查(即'j'循環)的上限應該是'i'而不是'arr_size',因爲在大於'i'的每個元素中都可以是內。 –

回答

2

更改爲:

for(int i=0;i<arr_size;i++) 
    { 
     cout<<"enter value of slot"<<i+1<<": "; 
     while(1) { //You must keep reading until you have read a valid value 
     cin>>value; 
     bool alreadyPresent = false;  

     for(int j=0;j<i;j++){ //You only have to check against already inserted values! 
           //Before you were checking against uninitialized values!! 
      if(value == aArray[j]) 
      { 
      alreadyPresent = true; 
      break; //I don't need to further iterate the array 
      } 

     } 

     if (alreadyPresent) 
      cout<< std::endl << value exists, please re enter: "; 
     else 
      break; //I can proceed with the next value, user has not to reenter the value 
     } 
    aArray[i] = value; 

    std::cout << std::endl; //next line... 
    } 

備選:

for(int i=0;i<arr_size;i++) 
    { 
     cout<<"enter value of slot"<<i+1<<": "; 

     bool alreadyPresent; 
     do { //You must keep reading until you have read a valid value 
     cin>>value; 
     alreadyPresent = false;  

     for(int j=0;j<i;j++){ //You only have to check against already inserted values! 
           //Before you were checking against uninitialized values!! 
      if(value == aArray[j]) 
      { 
      alreadyPresent = true; 
      cout<< std::endl << value exists, please re enter: "; 
      break; //I don't need to further iterate the array 
      } 

     } 

     } while (alreadyPresent); 
    aArray[i] = value; 

    std::cout << std::endl; //next line... 
    } 
+0

呵呵! @antonio謝謝,它的工作! – isme

+0

@Erbureth是的,肯定你是對的,否則它只會檢查第一個值 – Antonio

+0

@isme請檢查編輯建議的Erbureth – Antonio