您的位置:首页 > 编程语言 > C语言/C++

C语言从txt文本中读取多行用逗号分隔的数据

2016-11-08 19:53 691 查看
例如数据为:

0.5712,0.45356,0.74399

0.58775,0.4721,0.77793

0.51964,0.42228,0.69693

将每一列的数据保存在一个double型数组中。

解决方案:

1.利用fscanf()函数:

#include <stdio.h>
#include<stdlib.h>

int main()
{
FILE *fp = fopen("C://Users//aoe//Desktop//2016.920//796-40//clo.txt", "r");
if (fp == NULL)
{
printf("file open error\n");
return -1;
}

double xx[3];
double yy[3];
double zz[3];

for (int i = 0; i < 3; i++)
{
fscanf(fp, "%lf,%lf,%lf", &xx[i], &yy[i], &zz[i]);
printf("%lf,%lf,%lf\n", xx[i], yy[i], zz[i]);
}
fclose(fp);
system("pause");
return 0;
}


参考:

http://blog.csdn.net/liangxanhai/article/details/8026496

http://blog.csdn.net/tomorrow_begin/article/details/38878109

2.利用fgets()函数

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

double char2num(char *s);

int main()
{
int i, j = 0, k;
FILE*fp = fopen("C://Users//aoe//Desktop//2016.920//796-40//clo31.txt","r");
if (fp == NULL)
{
printf("file open errror/n");
return -1;
}
char buf[30];
char str[10];

double xx[176 * 144];
double yy[176 * 144];
double zz[176 * 144];

memset(str, 0, sizeof(str));
memset(buf, 0, sizeof(buf));

int number = 0;
double d = 0;
for (int n = 0; n < 25344;n++)
{
fgets(buf, sizeof(buf), fp);
for (i = 0; buf[i]; i++)
{
if (buf[i] != ',')
{
str[j] = buf[i];
j++;
}
else if (buf[i] == ',')
{
printf("%s\t", str);
d = char2num(str);
number++;
if (number == 1)
xx
= d;
else if (number == 2)
yy
= d;
memset(str, 0, sizeof(str));//void *memset(void *s,int c,size_t n) 总的作用:将已开辟内存空间 s 的首 n 个字节的值设为值 c。
j = 0;
}
}
printf("%s", str);
d = char2num(str);
zz
= d;
memset(str, 0, sizeof(str));
j = 0;
number = 0;
memset(buf, 0, sizeof(buf));
}
fclose(fp);
for (int i = 0; i < 25344; i++)
{
printf("%.5f\t", xx[i]);
printf("%.5f\t", yy[i]);
printf("%.5f\n", zz[i]);

}
system("pause");
return 0;

}

double char2num(char *s) //将字符型数据转换成double型数据
{
double d = 0;
int i, t = 0;
for (i = 0; s[i] != 0; i++)
{
if (s[i] == '.')
{
t = 10;
}
else
{
if (t == 0)
{
d = d * 10 + (s[i] - '0');
}
else
{
d = d + (double)(s[i] - '0') / t;
t *= 10;
}
}
}
return d;
}


此方案会存在数据转换错误的情况,不建议采用,方法一比较简单。

参考:

http://www.cnblogs.com/xiaolongchase/archive/2011/10/22/2221326.html

http://blog.csdn.net/wuyu1125/article/details/7610652
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐