如何使用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 (将#修改为@)