我需要帮助将数据点、x 和 y 值从 txt 文件获取到两个数组中。
目前,文本文件由 5 行组成,例如:
0.116
0.118
0.12
0.122
0.124
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
main(void)
{
FILE *inp; /* pointer to input file */
double item;
int cnt=0,y,d,i;
double array[300],swap;
/* Prepare files for input */
inp = fopen("testdoc.txt", "r");
/* Read each item */
while ( (fscanf(inp, "%lf", &item) == 1) && (!feof(inp)) ) {
array[cnt] = item;
cnt++;
}
for (int i = 0; i < cnt; i++)
{
printf("%lf\n",array[i]);
}
printf("The total number of inputs is %d",cnt);
fclose(inp); /* Close the files */
return (0);
}
这仅读取文件的前半部分,即 x 值。其中输出为
0.116000
0.118000
0.120000
0.122000
输入总数为4
但是,我想读取一个文本文件并将 x 和 y 值的值存储在两个不同的数组中。
新的文本文件将如下所示
0.116,-0.84009
0.118,4.862
0.12,-1.0977
0.122,0.22946
0.124,3.3173
我如何更改上面的代码以识别“,”符号后的 Y 值?并一次将两者添加到两个数组中?
最佳答案
我尝试编译您在pastebin上发布的代码,但由于您的while语句中缺少括号而收到错误。 这是一个简单的解决方法。 更大的问题在于 while 循环的情况。
fscanf
返回每次调用时转换和分配的输入项的数量。
当您修改代码以返回两个
值时,while循环中的条件fscanf(inp, "%lf,%lf", &v1,&v2) == 1
将失败并且不会进入循环。
请将 while 语句修改为(也包含缺少的“(”)..
while ( (fscanf(inp, "%lf, %lf", &v1, &v2) == 2) && (!feof(inp)) )
你应该可以走了!!!
此外,最好在 main
函数中包含 int
返回类型。
关于c - 如何在 C 编程中读取文本文件并将其存储在数组中(值以逗号分隔)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58545808/