comparison of two character arrays

why this code is not working. i want to display the either you entered same name or different name

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 #include <iostream.h>
main()
{
char name1[10];
char name2[10];
int i;
int equality=0;
cout<<"Please enter the 1st Name"<<endl;
cin>>name1;
cout<<"Please enter the 2nd Name"<<endl;
cin>>name2;
cout<<"You entered the 1st name "<<name1<<" and 2nd Name "<<name2;
for(i=0; name1[i]!='/0'||name2[i]!='/0'; i++)
{if(name1[i]!=name2[i]){
equality=1; 
break;}
}
if(equality==1){
cout<<" and both are different name"<<endl;
}
else{
cout<<" but it is the same name"<<endl;}

system("pause");
}
First of all, why doesn't your main have an int in the beginning and why are you using iostream.h? that headerfile is not standard and doesn't exist on all platforms. Second, your for loop will give you a multicharacter constant warning if you don't change it. Third, the reason your if statement isn't working is the == operator is not overloaded for char*. What I recommended is strncmp(you need the cstring header file) and will compare if both strings are equal to zero(in other words equal).
Last edited on
can you kindly show the syntax for strncmp please i've googled it but don't understand.
Ok, the arguments that strncmp requires is two strings of constant characters(in this case name1 and name2). Then you set how many characters you are going to compare(in this case 9 plus the null terminator dictated by the size of the array). Put it all together and you get if(strncmp(name1, name2, 10) == 0) {break;}

Note--Remember to include the cstring header file.
Last edited on

Thank you very much!!!!!!!!!
Topic archived. No new replies allowed.