嗨,我使用 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"
最佳答案
==
实际上只对比较整数值有用。使用诸如 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, " ");
}
}
关于指向字符串的指针的条件(if 语句),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19341968/