检查Substring是否多次出现在字符串中?

时间:2015-03-14 16:28:08

标签: c file parsing pointers

假设我有一个文件:

f56,5 d23,4

我正在获取'f'和逗号之后的值(和d一样),所以我这样做: (使用fgets读取文件时)

while (fgets(buf,100,file) != NULL)
{
    temp = strstr(buf,"f"); //where temp is a (char * )
    if(temp != NULL)
    {  
        //An int defined previously 
        x = atol(temp+1); //get the value 56
        temp = strstr(buf,","); //get the value 5
        y = atol(temp+1); //get the value 5
    }

    temp = strstr(buf,"d");
    if(temp != NULL)
    {
        a = atol(temp+1); //get the value 24
        temp = strstr(buf,","); //get the value 4?
        b = atol(temp+1); //get the value 4?
    }


}

然而,这种工作,a和b的值不正确,a有时是真的,但是b总是y的值(先前的逗号值)。我不确定如何继续这里,我尝试使用另一个指针在代码中使用strstr,但这似乎不起作用,任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

  

但是b始终是y(之前的逗号值)

的值

这是因为您开始再次从头开始搜索逗号,因此不会将逗号与'd'相关联,而是会再次与'f'关联。

要解决此问题,请替换此行

temp = strstr(buf, ","); //get the value 4?

用这个:

temp = strstr(temp+1, ","); //yes, get the value 4!

这将开始在'd'之后搜索下一个逗号,为您提供正确的结果。

相关问题