after using the search and everything, I tried to write my own little code that compares 2 strings.

#include <iostream>

using namespace std;

int main()
{
char stringa[12];
char stringb[13];

cout << "enter the data for string a " ;

    cin >> stringa;

cout << "enter the data for string b " ;

cin >> stringb;


if (stringa == stringb)
 {
   cout << "Match" << endl;
} 
else
 {
   cout << "No match" << endl;
}

return 0;

}

but for some reason it always returns no match!

Hello there,

It will always return no match, because the two pointers do not equal each other.

Think about it for a quick moment.... what is an array? An array is a pointer to a data structure with elements inside it.

For example:

stringa = pickle

stringa[1] == p
stringa[2] == i
stringa[3] == c

and so on

What you are trying to tell the computer is to "compare all of the elements from string a and see if they are the same in string b". The == operator is going to balk at this, as it is seeing your array name, and not the elements within.

You have two ways to do this...

METHOD 1:
* Write a FOR LOOP
---> count the amount of elements in string a

* Write another FOR LOOP
---> count the amount of elements in string b

* Do a quick compare....
---> if elements(a) <> elements(b) you know that they are not the same.
---> note that if someone puts a space after the last character before hitting return, it will garble up your code doing this. Remember, computers are precise! And they will make precisely the wrong decision that you expect.

* Write another FOR loop (remember that both strings are the same length)
--> compare stringa(n) == stringb(n) and break loop if they diverge

METHOD 2

Check out the strcmp function library. I think it returns a 1 if they are different, and 0 if they are not. MUCH EASIER!!

Christian

Just to summarize what Christian said ...

Strings are stored in memory as an array of characters. An array is referenced in C++ by a pointer to its first element in memory. The [] following the array's name represents its offset from this first element in memory. Therefore, when you are talking about stringa or stringb in your C++ program, you are talking about their memory locations. Because these two variables (in this situation) can never point to the same memory location, they can never be equal.

id use ANSI string instead of char arrays. This is the pre-defined standard c++ string class. They have the operators overloaded so you can use +, +=, == ect... on them.

sample code

#include <string>
using namespace std;

string str1;
string str2;

if(str1 == str2) // works 
{
}

/* you can also use += for easy combining */

str1 += str2; // combine str1 and str2 into str1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.