更改爲:
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...
}
使用['性病::設置'](http://en.cppreference.com/mwiki/index .php?title = Special%3ASearch&search = std%3A%3Aset)而不是原始整數數組。 –
你可能會考慮插入一個'std :: set'並檢查結果。即使是最小的變化,使用'std :: find'代替循環。另外請注意,如果在目前設置的元素中找不到元素,您正在讀取未初始化的數據。 – chris
或者您只需在數值再次輸入後引入'break'。但是你不會初始化你的錯誤,因此你的* exists *檢查(即'j'循環)的上限應該是'i'而不是'arr_size',因爲在大於'i'的每個元素中都可以是內。 –