首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数组中添加元素将不接受类似的元素。

数组中添加元素将不接受类似的元素。
EN

Stack Overflow用户
提问于 2018-03-10 14:55:17
回答 3查看 55关注 0票数 0

我练习在数组中添加元素,我确实添加了一个while循环,以防止添加数组中已经存在的元素,并且必须输入与数组不同的字符。问题是,在我的例子中,我输入一个字符'a‘,然后'b’之后,我试图再次输入'a‘,它接受了输入。它应该是不接受一个已经存在的元素,但它确实接受了。为什么会这样呢?提前感谢

这是我的密码

代码语言:javascript
复制
#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;
}
EN

Stack Overflow用户

发布于 2018-03-10 15:13:56

你应该在x=0 in while。所以

代码语言:javascript
复制
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;
            }
    }
票数 0
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49210421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档