Reputation: 389
I want to compare 2 string but when I do a strcmp
function, it tells me that:
'strcmp' : cannot convert parameter 1 from 'std::string'
How can I fix this?
Here is my code :
int verif_file(void)
{
string ligne;
string ligne_or;
ifstream verif("rasphone");
ifstream original("rasphone.pbk");
while (strcmp(ligne, "[SynCommunity]") != 0 &&
(getline(verif, ligne) && getline(original, ligne_or)));
while (getline(verif, ligne) && getline(original, ligne_or))
{
if (strcmp(ligne, ligne_or) != 0)
return (-1);
}
return (0);
}
Upvotes: 1
Views: 2034
Reputation: 42083
Your compiler gives you an error because strcmp
is a C-style function that expects arguments of type const char*
and there is no implicit conversion from std::string
to const char*
.
And although you might retrieve a pointer of this type using std::string
's c_str()
method, since you are working with std::string
objects, you should use the operator ==
instead:
if (ligne == ligne_or) ...
or comparison with const char*
:
if (ligne == "[Syn****]") ...
Upvotes: 7
Reputation: 1552
I like the boost algorithm library.
#include <boost/algorithm/string.hpp>
std::string s1("This is string 1");
std::string s2("this is string 2");
namespace balg = boost::algorithm;
// comparing them with equals
if( balg::equals( s1, s2 ) )
std::cout << "equal" << std::endl;
else
std::cout << "not equal" << std::endl;
// case insensitive version
if( balg::iequals( s1, s2 ) )
std::cout << "case insensitive equal" << std::endl;
else
std::cout << "not equal" << std::endl;
Upvotes: 2
Reputation: 227418
Just use std::string
's operator==
:
if (ligne == "[SynCommunity]") ...
if (ligne == ligne_or) ...
Upvotes: 7
Reputation: 1307
If you want to use strcmp, then try
if (strcmp(ligne.c_str(), ligne_or.c_str()) != 0)
...
Upvotes: 5
Reputation: 96810
Change
if (strcmp(ligne, ligne_or) != 0)
to
if (ligne != ligne_or)
Upvotes: 5