从C中的文本文件中读取逗号分隔的值 [英] Read comma separated values from a text file in C
本文介绍了从C中的文本文件中读取逗号分隔的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ $ p $ $ $ $ $ $ $ $ $ $ $ $ / code>
在C中,并尝试将它们作为字符串和int参数传递给一个函数。我曾尝试使用sscanf(),甚至没有太多的帮助与fgetc()操作。
<$ c在逗号后面的空格被证明是一个问题。 $ c> 2001,102
1314,78
0410,910
...
请帮助我。
谢谢。
解决方案
#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); (i = 0; i <2; i ++)
{
if(i == 0)
{
printf(%s \ t ,令牌);
token = strtok(NULL,s);
} else {
printf(%d \ n,atoi(token));
}
}
}
fclose(fp);
} else {
perror(user.dat);
$ / code $ / pre
$ b $ user.dat file:
1000,76
0095,81
2910,178 p>
0001,1 1
输出:
1000 76
0095 81
2910 178
0001 1
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.
解决方案 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
这篇关于从C中的文本文件中读取逗号分隔的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文