Reputation: 241
I have a program which search through an array to find a word match
char *mywords []={"Dog","Cat","etc"};
string search;
cout<<"enter a word to search"<<endl;
cin>>search;
for(int n=0;n<3;n++)
{
if(search==mywords[n])
{
cout<<mywords[n]<<"found"<<endl;
}
}
It works but I am wondering
string search;
to char *search=new char;
or char search[4];
it never finds the wordchar* word("Dog");
and string word("Dog");
.Upvotes: 1
Views: 2971
Reputation: 126502
FIRST QUESTION:
a) why it doesn't work when I change the part
When you use char*
, the expression:
search == mywords[n]
Is comparing two pointers of type char*
, and not the actual zero-terminated strings pointed to by those pointers.
When you use std::string
, on the other hand, the overloaded operator ==
that accepts an std::string
object and a const char*
pointer is picked, and proper string comparison is performed.
Besides, keep in mind that you always have to delete
objects allocated with new
, or you will have a memory leak. This is just another reason why using std::string
is preferable.
SECOND QUESTION:
b) what's the different between
char* word("Dog");
andstring word("Dog");
In the first case, you are initializing a pointer word
to point to the first character of the string literal "Dog"
- notice, that the type of word
should be const char*
, and not char*
; this implict conversion is deprecated in C++03 and illegal in C++11.
In the second case, you are constructing an object word
of type std::string
and passing the "Dog"
string literal in input to std::string
's constructor. The constructor will, in turn, allocate a separate buffer where to copy the original string literal passed as an argument.
Upvotes: 2