C语言 从 C 中的文本文件中读取逗号分隔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26443492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read comma separated values from a text file in C
提问by Souradeep Sinha
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:
我对 C 编程真的很陌生,这是作业的一部分。我正在尝试以以下格式读取逗号分隔的文本文件:
[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.
在 C 中并尝试将它们作为 string 和 int 参数传递给函数。我曾尝试使用 sscanf() 甚至使用 fgetc() 进行操作而没有太多帮助。逗号后面的空格被证明是一个问题。
Example:
例子:
2001, 102
1314, 78
0410, 910
...
Please help me out.
请帮帮我。
Thank you.
谢谢你。
回答by Souradeep Sinha
Thanks to @rubberboots for the help.
感谢@rubberboots 的帮助。
#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:
user.dat 文件:
1000, 76
1000, 76
0095, 81
0095, 81
2910, 178
2910, 178
0001, 1
0001, 1
Output:
输出:
1000 76
1000 76
0095 81
0095 81
2910 178
2910 178
0001 1
0001 1

