[英]Problems with the comparison of two strings using strcmp
I want to compare 2 string but when I do a strcmp
function, it tells me that: 我想比较2个字符串,但是当我执行strcmp
函数时,它告诉我:
'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);
}
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*
. 您的编译器给您一个错误,因为strcmp
是C风格的函数,期望使用const char*
类型的参数,并且没有从std::string
到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: 并且尽管您可以使用std::string
的c_str()
方法检索此类型的指针,但是由于您正在使用std::string
对象,因此应使用==
运算符 :
if (ligne == ligne_or) ...
or comparison with const char*
: 或与const char*
比较:
if (ligne == "[Syn****]") ...
Just use std::string
's operator==
: 只需使用std::string
的operator==
:
if (ligne == "[SynCommunity]") ...
if (ligne == ligne_or) ...
Change 更改
if (strcmp(ligne, ligne_or) != 0)
to 至
if (ligne != ligne_or)
If you want to use strcmp, then try 如果要使用strcmp,请尝试
if (strcmp(ligne.c_str(), ligne_or.c_str()) != 0)
...
I like the boost algorithm library. 我喜欢Boost算法库。
#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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.