我练习在数组中添加元素,我确实添加了一个while循环,以防止添加数组中已经存在的元素,并且必须输入与数组不同的字符。问题是,在我的例子中,我输入一个字符'a‘,然后'b’之后,我试图再次输入'a‘,它接受了输入。它应该是不接受一个已经存在的元素,但它确实接受了。为什么会这样呢?提前感谢
这是我的密码
#include<iostream>
using namespace std;
int main(){
char array[5] = {'a','a','a','b','b'};
char add;
for(int x = 0; x<5; x++){
cout<<"[" <<array[x] <<"]";
}
cout<<endl;
cout<<"Add element: ";
cin>>add;
//if the element is already existing, prompt user to input again
for(int x =0 ;x<5;x++){
while(add==array[x]){
cout<<"Already Exist and its in position " <<x+1 <<" Please add a different character: ";
cin>>add;
}
}
array[5] = add; //adding the element in the last position
//if adding succesfull, display the new element
cout<<"==========================================" <<endl;
cout<<"Adding Succesful! Your new array is" <<endl;
for(int x = 0; x<=5; x++){
cout<<"[" <<array[x] <<"]";
}
cout<<endl;
cout<<"==========================================" <<endl;
}发布于 2018-03-10 15:13:56
你应该在x=0 in while。所以
for(int x =0 ;x<5;x++){
while(add==array[x]){
cout<<"Already Exist and its in position " <<x+1 <<" Please add a different character: ";
cin>>add;
x=0;
}
}https://stackoverflow.com/questions/49210421
复制相似问题