文件扫描多行时跳过线条

时间:2013-04-21 05:14:36

标签: c file line skip fault

只要文件格式为

,此代码就会读取文件并打印出来
word,12,34
words,40,20
another,20,11

如果它之间有一条空行,如何让它做同样的事情,因为现在它只是给我一个分段错误

word,12,34

words,40,20

another,20,11



#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
    FILE *pdata;
    char buffer[1000];
    char *token, *del=",";
    int value1;
    double value2;


    pdata = fopen ("file.data", "r");

    if(pdata == NULL)
    {
        printf("unable to open file \n");
        exit(1);
    }

    while( fgets(buffer, sizeof(buffer), pdata) != NULL )
    {
        token = strtok(buffer, del);
        value1 = atoi( strtok(NULL, del) );
        value2 = atof( strtok(NULL, del) );

        printf("%s is %.3lf\n", token, value1 + value2);

    }

    fclose( pdata );


return 0;
}   

请帮助

2 个答案:

答案 0 :(得分:1)

我会做出两个改变:

char *del = ", "; // test for either space or comma

(根据我之前对这个问题的评论):

while( fgets(buffer, sizeof(buffer), pdata) != NULL )
{
    char *temp;
    token = strtok(buffer, del);
    if (token != NULL) {
      temp = strtok(NULL, del);
      if (temp) value1 = atoi( temp );
      temp = strtok(NULL, del);
      if (temp) {
        value2 = atof( temp );
        printf("%s is %.3lf\n", token, value1 + value2);
      }
}

如果未找到令牌,strtok将返回NULL。我猜测,将NULL字符串传递给atoi正在给你一个seg错误。像这样,我们绝对肯定不会发生。我测试了这个并且它有效。

答案 1 :(得分:0)

while( fgets(buffer, sizeof(buffer), pdata) != NULL )
{
    if (buffer[0] == '\n') {
        /* empty line */
        continue;
    }
    token = strtok(buffer, del);
    value1 = atoi( strtok(NULL, del) );
    value2 = atof( strtok(NULL, del) );

    printf("%s is %.3lf\n", token, value1 + value2);

}