-1

我正在创建一个 c++ 数组程序,在该程序中我试图从用户那里获取输入,但在插入过程中我想提示用户输入重复值。我在里面使用了一个while循环和for循环,但是如果用户输入了重复的值,它就不起作用了。他将被要求在特定索引处再次输入值。

int size=0;
int k;
int index=0;
int temp=0;
int aray1[2];
char ch='y';
while(ch='y') {
    for(k=0; k<=2; k++)
    {
        if(aray1[k]==temp) {
            cout<<"please do not enter duplicates";
            ch='y';
            index--;
        } else {
            aray1[index]=temp;
            index++
            ch='n';
        }


    }

    system("pause");
}
4

1 回答 1

2

我会改用std::vector

#include<iostream>
#include<vector>
#include<algorithm>

int main(){
  using namespace std;
  vector<int> v;

  int size=2;    

  while(v.size()<size){
    int i;
    cin >> i;
    vector<int>::iterator it = find(v.begin(), v.end(), i);

    if(it==v.end()) // i is not in v so insert it to the end of the vector.
      v.push_back(i);
    else
      cout << "Duplicate entered." << endl;
  }
}

http://www.cplusplus.com/reference/algorithm/find/

于 2013-09-25T08:16:00.273 回答