数组的重复名称检查功能

时间:2019-03-08 17:42:23

标签: c++

我仍然是C ++的初学者,如果问题很简单,我感到抱歉。

我正在尝试构建一个程序,要求您输入名称并将其注册到数组。然后,我需要调用一个函数来检查是否存在重复的名称。如果有,它会要求用户输入其他名称。

我遇到的问题是该函数是否存在重复调用,并且总是替换输入的名字。

int checking(string stringArray[5]) {
int i, z ;
for (i = 0; i < 5; i++) {
    for (z = 0; z < 5; z++) {
        if (z != i) { // Makes sure don't check number against itself
            if (stringArray[z] == stringArray[i]) {
                return i;
            }
            else {
                return 0;
int main(){ 
 for (i = 0; i < 5; i++) {
    cin >> stringArray[i];
}
 j = checking(stringArray);
  if (j == 0) {
    cout << "Please re-enter name " << ". Duplicate names are not allowed" 
    <<'\n';
    cin >> stringArray[j];

} 

1 个答案:

答案 0 :(得分:0)

Some observations (ignoring the syntax errors, I assume these are not present in your actual code):

  1. z doesn't need to start at 0 every time, it can start at i + 1 because you dont need to check pairs you have already checked (makes it simpler and runs faster)
  2. you don't want to return in your loop, it will prevent you from checking past the first repeated name. Instead move your reenter statement into the loop.
  3. generally you dont want to use literals (5) in a loop, instead use a variable to store the length of the array and compare to that (this is just a general programming rule, it won't change how the code runs)

Your final checking() function should look closer to:

void checking(string stringArray[5]) {
    int i, z ;
    // consider replacing 5 with a variable
    for (i = 0; i < 5; i++) {
        for (z = i+1; z < 5; z++) {
            if (stringArray[z] == stringArray[i]) {
                cout << "Please re-enter name " << 
                ". Duplicate names are not allowed" <<'\n';
                cin >> stringArray[z];
                /* restart the loop user may have entered a */ 
                /* second duplicate from previous entries */
                i = 0;
                z=i+1;
            }
        }
    }
}