问题
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