使用strcmp比较两个字符串的问题

ley*_*kan 1 c++ string comparison string-comparison strcmp

我想比较2个字符串但是当我做一个strcmp函数时,它告诉我:

'strcmp' : cannot convert parameter 1 from 'std::string'
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

这是我的代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

Lih*_*ihO 7

你的编译器给你一个错误,因为strcmp是C风格的函数,预计类型的参数const char*并没有隐式转换从std::stringconst char*.

虽然你可能会检索该类型使用指针std::stringc_str()方法,因为你正在使用std::string的对象,您应该使用操作符==来代替:

if (ligne == ligne_or) ...
Run Code Online (Sandbox Code Playgroud)

或与之比较const char*:

if (ligne == "[Syn****]") ...
Run Code Online (Sandbox Code Playgroud)


jua*_*nza 7

只是用std::string's operator==:

if (ligne == "[SynCommunity]") ...

if (ligne == ligne_or) ...
Run Code Online (Sandbox Code Playgroud)


0x4*_*2D2 5

更改

if (strcmp(ligne, ligne_or) != 0)
Run Code Online (Sandbox Code Playgroud)

if (ligne != ligne_or)
Run Code Online (Sandbox Code Playgroud)


Way*_*ang 5

如果你想使用strcmp,那就试试吧

if (strcmp(ligne.c_str(), ligne_or.c_str()) != 0)
   ...
Run Code Online (Sandbox Code Playgroud)