Hi. I'm trying to check for duplicates and prevent them from being added in my array. I wrote a loop in the addin function to check if a name is a duplicate and display a message asking you re-enter. When i run the code though each time a name is entered the message is displayed whether its a duplicate or not. Any suggestion would be appreciated
@Kwaku42
Please pick a language: C++ or C. (I recommend you get rid of all the <stdio.h> stuff and stick with C++ I/O. It's loads easier.)
You are always getting the message because on line 44 you initialize answer to true. Lines 48-50 don't change that. Instead, initialize with false -- this is the default value if lines 48-50 find no duplicate.
#include <iostream>
#include <cstring>
usingnamespace std;
void check(char[3][10], char[10]);
int main()
{
char name[3][10];
char trial[10];
strcpy(name[0], "Helen");
std::strcpy(name[1], "Fred");
strcpy(name[2], "Margaret");
cout << "Please enter a name: ";
cin >> trial;
for(int i = 0; i < 3; i++)
{
cout << name[i] << '=' << trial;
if(strcmp(name[i], trial))
cout <<" match not found yet\n";
else
cout << " match found <--\n";
}
//ANOTHER WAY
check(name, trial);
return 0;
}
void check( char list[3][10], char try_me[10])
{
for(int i = 0; i < 3; i++)
{
cout << list[i] << '=' << try_me;
if(strcmp(list[i], try_me))
cout <<" Match not found yet\n";
else
cout << " Match found <--\n";
}
return;
}
Please enter a name: Helen
Helen=Helen match found <--
Fred=Helen match not found yet
Margaret=Helen match not found yet
Helen=Helen Match found <--
Fred=Helen Match not found yet
Margaret=Helen Match not found yet
Program ended with exit code: 0