string not comparing perfectly

It is not comparing strings perfectly e.g if i type string1=eng and string2=english the output results in both are same.

int main()

{
char string1[5],string2[5];
int i,temp = 0;
cout << "Enter the string1 value:\n";
gets(string1);
cout << "\nEnter the String2 value:\n";
gets(string2);

for(i=0; string1[i]!='\0'; i++)
{
if(string1[i] == string2[i])
temp = 1;
else
temp = 0;
}

if(temp == 1)
cout<< "Both strings are same.";
else
cout<< "Both string not same.";

return 0;

}
Problem:
i   string1[i]   string2[i]   temp
0       't'       't'          1
1       'e'       'e'          1
2       's'       's'          1
3       't'       't'          1
4       'i'       '\0'         0
5       'n'     undefined    1 or 0
6       'g'     undefined    1 or 0
7       '\0'    undefined     -||-

temp = 1 or 0

Solution: End loop as soon it gets to the end of any of strings:
for(i=0; string1[i]!='\0' && string2[i]!='\0'; i++)

Problem:
i   string1[i]   string2[i]   temp
0       't'       't'          1
1       'e'       'a'          0
2       's'       'a'          0
3       't'       't'          1
4       '\0'       '\0'       -||-

temp = 1

Solution: Break out of loop as soon temp becomes 0:
1
2
3
4
5
6
if (string1[i] == string2[i])
    temp = 1;
else {
    temp = 0;
    break;
}


Problem:
i = 1, string1[i] = 'e'
'e' == 'e' -> temp = 1

i = 2, string1[i] = 'n'
'n' == 'n' -> temp = 1

i = 3, string1[i] = 'g'
'g' == 'g' -> temp = 1

i = 4, string1[i] == '\0'
end of loop

temp = 1

Solution: One extra condition after the loop to handle different string lengths.
1
2
if ((temp == 1) && (string1[i]!='\0' || string2[i]!='\0'))
    temp = 0;


Btw "english" - 7 chars + null char = 8, but string2[5]
Last edited on
Topic archived. No new replies allowed.