Comparing Two Strings

I am a beginner and would like to ask a question

My Code:
/////////////////////////
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<"Enter The Password\n";
char a[10];
cin>>a;
char b[]="rain";
if(a==b)
cout<<"\nRIGHT";
else
cout<<"WRONG";
getch();
}
///////////////

When I enter "rain" it shows "WRONG".
Thanks For Help
closed account (o3hC5Di1)
Hi there,

You are trying to compare c-strings, which are basically arrays of type char.
This can't be done just using a==b, because the name of an array actually holds the memory address to the first element of the array.

So in your case, you're actually asking "is the address of array a the same as that of array b?", which is off course not the case.

The recommended solution is to use std::string, which will allow you to do such comparison:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/////////////////////////
#include<iostream.h>
#include<conio.h>
#include <string> //include this
void main()
{
clrscr();
cout<<"Enter The Password\n";
//char a[10];
std::string a;
cin>>a;
//char b[10];
std::string b;
if(a==b)
cout<<"\nRIGHT";
else
cout<<"WRONG";
getch();
}
/////////////// 


Hope that helps.

All the best,
NwN
Topic archived. No new replies allowed.