Comparing multiple char arrays in C++
I'm creating a program which consists of comparing three character arrays, the code is this:
#include <iostream>
#include <string.h>
using namespace std;
#define MAX 20
int main()
{
char c1[MAX], c2[MAX], c3[MAX];
cout << "Introduce array 1: ";
cin >> c1;
cout << "Introduce array 2: ";
cin >> c2;
cout << "Introduce array 3: ";
cin >> c3;
if (strcmp(c1, c2)==0 && strcmp(c1, c3) == 0)
{
cout << "The three arrays are equal" << endl;
}
else
{
if (strcmp(c1, c2) != 0 && strcmp(c1, c3) != 0)
{
cout << "The three arrays are different" << endl;
}
else
{
if (strcmp(c1, c2) == 0 && strcmp(c1, c3) != 0)
{
cout << "1 and 2 are equal" << endl;
}
else
{
if (strcmp(c1, c2) != 0 && strcmp(c1, c3) == 0)
{
cout << "1 and 3 are equal" << endl;
}
else
{
if ((strcmp(c1, c2) != 0) && (strcmp(c2, c3) == 0))
{
cout << "2 and 3 are equal" << endl;
}
}
}
}
}
return 0;
}
The thing is that I don't know why when c2 and c3 are equal and c1 is different it tells me they're all different, in all the other cases it works fine, but I don't know what am I doing wrong.
Always comparing two pairs duplicates the effort – and you don't cover all possible pairs. Better:
if c1 == c2:
if c2 == c3:
all equal
else:
c3 differs from c1 and c2
else:
// now c1 and c2 differ in any case!
if c1 == c3:
c2 differs from c1 and c3
else:
// c1 and c2 differ, c1 and c3 differ
// but c2 and c3 could still be equal
if c2 == c3:
c1 differs from c2 and c3
else:
all three differ from one another