-1

嗨,我使用 strtok 拆分了我使用 fgets 从文件中读取的一行。我想知道如何使用 if 语句来检查行的每个分区。

文件中的一行类似于

1 名-姓

char *stuff;
while(fgets(buffer, sizeof(buffer), myfile)){
    stuff = strtok(buffer, " ");// this should give me 1
    if( ...... ) // what would be the correct way of saying if stuff == "1"
4

1 回答 1

0

==实际上只对比较整数值有用。使用类似strcmp(), 或strstr()进行字符串比较。

像这样的东西。 (请参阅嵌入的评论以获取一些解释......)

char *stuff;
char keep[260];// or some reasonable size to do your comparison.  
               //its best not to use your token to do anything except store the token :)
while(fgets(buffer, sizeof(buffer), myfile))
{
    stuff = strtok(buffer, " ");// this should give me 1
    while(stuff) // as long as stuff not NULL
    {
        strcpy(keep, stuff);//
        if(strcmp(keep, "1") == 0)  //strtok returns only (char *) and output of strcmp is 0 for equal
        {
            //do something here!
        }
        //get next token
        stuff = strtok(NULL, " ");
    }
}
于 2013-10-13T04:57:56.420 回答