0

我想在 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)
4

2 回答 2

3

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

于 2012-05-15T21:25:59.593 回答
2

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

于 2012-05-15T21:26:42.563 回答