A few issues to rectify include:
for (string input : names)
creates a temporary variable and fails to modify the original array; use for (string &input : names)
to create a reference to each array element in the loop block.
- Your
for
loops aren't nested, so there's no grounds for comparison between some element of the array (or an input
string) against every other element. Either nest your second loop inside your input
loop to perform the checks as you add names, or separate the check into its own block. Note that there are more efficient ways of solving this, such as keeping an unordered_set
of names you've seen; nested loops grow in exponential time complexity.
- Your second
for
loop's termination condition isn't testing anything helpful as it stands (it evaluates to 0
which is false
, terminating the loop immediately). Iterating until the counter meets or exceeds the length of the array, 5
, is more appropriate.
#include <iostream>
int main() {
std::string names[5];
for (std::string &input : names) {
std::cout << "Please enter a name: ";
std::cin >> input;
}
for (int i = 0; i < 5; i++) {
for (int j = i + 1; j < 5; j++) {
if (names[i] == names[j]){
std::cout << names[i] << " is a duplicate name!" << std::endl;
}
}
}
}
Output:
Please enter a name: a
Please enter a name: b
Please enter a name: c
Please enter a name: d
Please enter a name: a
a is a duplicate name!
Try it