comparing two char arrays not using <string.h>

hi this is my first post and thank you for taking a look, my c++ prof. wants to make a code for comparing two char arrays to see if they are exactly the and print if they the same or are different and I cannot for the life of me do this. This is what i got so far(sorry for my english)

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
const int arraysize=20;
char strOne[arraysize],strTwo[arraysize];
int counter=0,counter2=0;

cout<<"Enter the first string: ";
cin.getline(strOne,arraysize-1);
cout<<endl;
cout<<"Enter the second string: ";
cin.getline(strTwo,arraysize-1);
cout<<endl;

for(int i=0;strOne[i]!='\0';i++)
counter=i;

for (int j=0;strTwo[j] !='\0';j++)
counter2=j;

counter=counter+1;
counter2=counter2+1;

cout<<"-------------------------------------------"<<endl;
cout<<"The 1st string is: ";
cout<<strOne<<endl;
cout<<"It contains "<<counter<<" characters"<<endl;
cout<<"The 2nd string is: ";
cout<<strTwo<<endl;
cout<<"It contains "<<counter2<<" characters\n"<<endl;


return 0;
}
closed account (zb0S216C)
The logic is simple: Iterate through each array an compare the corresponding character of array a against array b. If the two match, do your thing, if not, do your thing.

Comparison is the key here. During each cycle of the loop that performs the comparison, make sure you handle the case when two characters don't match. For this to work, you may want to include a new bool object that indicates whether or not the two arrays match. Here's a example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool match( true );

for( int i( 0 ); i < length_of_arrays; ++i )
{
    if( array_ai is not equal to array_bi )
    {
        // Set 'match' to 'false';
        // Break from the loop;
    }
}

if( /*'match' is not equal to 'false'*/ )
{
    // Inform the user;
}


Wazzak
Last edited on
thanks a lot it finally worked I did this and it worked perfectly:

for(int g=0;g<=arraysize;g++){
if(strOne[g]!=strTwo[g])
{
cout<<"The strings are different"<<endl;
break; }
if(g==counter && g==counter2)
cout<<"The strings are the same"<<endl;
}
Topic archived. No new replies allowed.