if i have two strings say:

string str1,str2;

then how can i compare them by using strcmp function?

if i have two strings say:

string str1,str2;

then how can i compare them by using strcmp function?

The strcmp() works with C strings. The string class has comparison built in using both operators and the compare() method. The compare() method is the closest match to strcmp(), but if you still want to use strcmp(), call the c_str() method to get a C string from a string object.

int cmp = strcmp(str1.c_str(), str2.c_str());

Why would you want to do that when you can simply use the relational operators :

#include <iostream>
#include <string>
using namespace std;

int main(){		
	string s = "100";
	string n = "200";
	
	cout << boolalpha;
	cout << "s == n : " << (s == n) << endl;
	cout << "s <= n : " << (s <= n) << endl;
	cout << "s >= n : " << (s >= n) << endl;
	cout << "s != n : " << (s != n) << endl;
}

Do you really need to use strcmp? String's have a built in operator == that you can use for comparison.

std::string foo = "foo";
std::string bar = "bar";
if (foo == bar)
    std::cout << "foo and bar are equal.";
else
    std::cout << "foo and bar are not equal.":

^^^ firstPerson beat me to it ^^^

Edited 6 Years Ago by NathanOliver: n/a

This question has already been answered. Start a new discussion instead.