微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用getline()函数在字符串数组中查找重复项?

如何解决如何使用getline()函数在字符串数组中查找重复项?

我想在数组字符串 (name[times]) 中输入一个名称,并且我想检查该名称是否重复,以便用户可以更改他之前输入的名称。当我使用函数“cin>>name[times]”时,代码会正确检查重复。但是当我使用 getline(cin.ignore(),name[times]) 时,重复检查无法正常工作。这是代码中究竟发生了什么的例子。 enter image description here

string name[1000];
int times = 0;
int hold = 1;
int repeat = 1;
int option;
int j,i;

while( hold != 0){

   do{
    cout<<"Enter Name: "<<endl;
   // cin>>name [times]; 
 getline(cin.ignore(),name[times]);
    cout<<"Name"<<"["<<times<<"]"<<endl<<endl;

//检查是否重复

    if (times > 0){
            
        for( i = times ; i >= 0 ; i--){
        for( j = i - 1 ; j >= 0 ; j--){
        
           if(name[i] == name[j]){
            cout<<"It already exists. Please try again"<<endl;
        times -= 1;  
        repeat = 0;
               
             }
        }}}else{
        repeat = 0;
        }
        }while (repeat != 0);       
            
  
    cout<<"[1] to Add "<<endl;
    cout<<"[2] to Stop"<<endl;
    cin>>option;
    

     if (option == 1){
        times++;
        hold = 1;
    }else{
        hold = 0;
    }}



// display

for (i = 0 ; i <= times ; i++ ){

    cout<<"["<<i<<"]"<<name[i]<<endl;

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。