strstr C功能异常

strstr C功能异常,c,text-parsing,strstr,C,Text Parsing,Strstr,对于即将到来的C项目,目标是读取CSV文件,前两行列出行和列的长度,如 attributes: 23 lines: 1000 e,x,y,n,t,l,f,c,b,p,e,r,s,y,w,w,p,w,o,p,n,y,p e,b,y,y,t,l,f,c,b,n,e,c,s,s,w,w,p,w,o,p,n,s,m e,x,f,y,t,l,f,w,n,w,t,b,s,s,w,w,p,w,o,p,n,v,d e,s,f,g,f,n,f,c,n,k,e,e,s,s,w,w,p,w,o,p,k,v,u 问题

对于即将到来的C项目,目标是读取CSV文件,前两行列出行和列的长度,如

attributes: 23
lines: 1000
e,x,y,n,t,l,f,c,b,p,e,r,s,y,w,w,p,w,o,p,n,y,p
e,b,y,y,t,l,f,c,b,n,e,c,s,s,w,w,p,w,o,p,n,s,m
e,x,f,y,t,l,f,w,n,w,t,b,s,s,w,w,p,w,o,p,n,v,d
e,s,f,g,f,n,f,c,n,k,e,e,s,s,w,w,p,w,o,p,k,v,u
问题是,我不知道将来的文件输入是否具有相同的行/列长度,因此我正在实现一个
determineFormat
函数来读取前两行,这将用于构建数据结构

为此,我需要将一个子字符串与当前行匹配。如果匹配,则使用
fscanf
读取该行并提取长度整数。但是,此代码不起作用,因为整个
strstr
函数在ddd中被跳过

int lineCount, attrCount; //global variables

void determineFormats(FILE *incoming){

    char *curLine= emalloc(CLINPUT);
    int i;
    char *ptr=NULL;

    for (i=0; i<2; i++){
        if (fgets(curLine, CLINPUT, incoming) != NULL){
            ptr= strstr(curLine, "attrib");  //this line is skipped over

            if (ptr!= NULL)
                fscanf(incoming, "attributes: %d", &attrCount);

            else 
                fscanf(incoming, "lines: %d", &lineCount);  

        }
    }

    printf("Attribute Count for the input file is: %d\n", attrCount);
    printf("Line count is: %d\n", lineCount);

}

一旦发生这种情况,线路指示器消失,从该点开始的单步(F5)返回调用函数。

strstr工作正常。问题是fscanf将读取下一行,因为当前行已经读取

这里有更正确的方法

for (i=0; i<2; i++){
    if (fgets(curLine, CLINPUT, incoming) != NULL){
        if (strstr(curLine, "attributes:")) {
            sscanf(curLine, "attributes: %d", &attrCount);
        } else if (strstr(curLine, "lines:")) {
            sscanf(curLine, "lines: %d", &lineCount);  
        }

    }
}

for(i=0;iErm,那不是CSV文件。stackoverflow的粗体迷你标记中逗号分隔的值bug=)应该使用非贪婪的regexesYeah。。。我认为这仍然说明了问题:)是的。你的定义是100%正确的。在网站上看到bug真是太好了。你忘了在那里释放内存了……正是fscanf对sscanf的更改成功了!谢谢
for (i=0; i<2; i++){
    if (fgets(curLine, CLINPUT, incoming) != NULL){
        if (strstr(curLine, "attributes:")) {
            sscanf(curLine, "attributes: %d", &attrCount);
        } else if (strstr(curLine, "lines:")) {
            sscanf(curLine, "lines: %d", &lineCount);  
        }

    }
}