0

if i have two strings say:

string str1,str2;

then how can i compare them by using strcmp function?

6
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by NathanOliver
0

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());
0

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;
}
0

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 by NathanOliver: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.