0

只要文件是这种格式,此代码就会读取文件并打印它

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;
}   

请帮忙

4

2 回答 2

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是什么给你的段错误,我猜。像这样,我们绝对确保不会发生这种情况。我对此进行了测试,并且可以正常工作。

于 2013-04-21T05:31:41.093 回答
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);

}
于 2013-04-21T05:20:53.027 回答