2014-07-16 51 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