Read comma separated values from a text file in C [duplicate]

旧城冷巷雨未停 提交于 2019-12-06 13:43:07

问题


I am really new to C programming and this is a part of an assignment. I am trying to read a comma separated text file in the format:

 [value1], [value2]

in C and trying to pass them as string and int parameter into a function. I have tried using the sscanf() and even manipulation with fgetc() without much help. The space after the comma is proving to be a problem.

Example:

 2001, 102
 1314, 78
 0410, 910
 ...

Please help me out.

Thank you.


回答1:


Thanks to @rubberboots for the help.

#include <stdio.h>
#include <string.h>

void main()
{
    FILE *fp = fopen("user.dat", "r");
    const char s[2] = ", ";
    char *token;
    int i;
    if(fp != NULL)
    {
        char line[20];
        while(fgets(line, sizeof line, fp) != NULL)
        {
            token = strtok(line, s);
            for(i=0;i<2;i++)
            {
                if(i==0)
                {   
                    printf("%s\t",token);
                    token = strtok(NULL,s);
                } else {
                    printf("%d\n",atoi(token));
                }       
            }
        }
        fclose(fp);
    } else {
        perror("user.dat");
    }   
}   

user.dat file:

1000, 76

0095, 81

2910, 178

0001, 1

Output:

1000 76

0095 81

2910 178

0001 1



来源:https://stackoverflow.com/questions/26443492/read-comma-separated-values-from-a-text-file-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!