我仍然是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];
}
答案 0 :(得分:0)
Some observations (ignoring the syntax errors, I assume these are not present in your actual code):
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;
}
}
}
}