Case 1 : Enter string 1 : hi Enter string 2 : hello Strings are not equal. Case 2 : Enter string 1 : 12345 Enter string 2 : 12345 Strings are equal! Case 3 : Enter string 1 : STRING Enter string 2 : string Strings are not equal.
This is a C++ Program to Compare Two Given Strings for Equality.
The program takes two strings and checks for their equality.
1. The program takes two strings.
2. Using string function, the two strings are compared.
3. The result is printed.
4. Exit.
Here is the source code of C++ Program to Compare Two Given Strings for Equality. The program output is shown below.
#include<iostream.h>
#include<string.h>
using namespace std;
int main ()
{
char str1[50], str2[50];
cout<<"Enter string 1 : ";
gets(str1);
cout<<"Enter string 2 : ";
gets(str2);
if(strcmp(str1, str2)==0)
cout << "Strings are equal!";
else
cout << "Strings are not equal.";
return 0;
}
1. The user is asked to enter two strings and stored in ‘str1’ and ‘str2’.
2. Using an inbuilt function strcmp() under the library string.h, the two strings are compared for equality.
3. The result is then printed if they are equal are not.
Case 1 : Enter string 1 : hi Enter string 2 : hello Strings are not equal. Case 2 : Enter string 1 : 12345 Enter string 2 : 12345 Strings are equal! Case 3 : Enter string 1 : STRING Enter string 2 : string Strings are not equal.