比较 strtok 之后的字符串

Comparing strings after strtok

本文关键字:字符串 之后 strtok 比较      更新时间:2023-10-16

我想在 strtok 之后比较字符串,但我似乎得到了假而不是真

如果我使用 strtok,我还需要做什么吗?

char file[] = "temp.txt";
ifstream getfile;
getfile.open(file,ios::in);
if(getfile.is_open())
{
        char data[256];
    char *line;
    const char * test = "init";
    //loop till end of file                   
    while(!getfile.eof())
    {
        //get data and store to variable data
            getfile.getline(data,256,'n');
        line = strtok(data," ");
        while(line != NULL)
        {
            cout << "Comparing " << line << " with " << test <<endl;
            //This is suppose to print but it dosent
            if(line == test)
                cout << line << endl;
            line = strtok(NULL," ");
        }
    }
}

输出:

 comparing init with init

想要的输出:

 comparing init with init
 init

谢谢!:D

====

============================

更改为以下内容,它奏效了! :)

if(strcmp(line,test)==0)

您正在比较指针而不是内容。查看 strcmp 或将 C 字符串包装在 std::string 中。

您正在比较指针(字符串的地址)。 他们永远是不同的。 使用 strcmp() 比较字符串本身。