[英]How do I read a text file and store it in an array in C programming (values seperated by a comma)?
I need help with getting datapoints, x and y values from a txt file into two arrays.我需要帮助将 txt 文件中的数据点、x 和 y 值放入两个 arrays。
Currently, the text file consists of 5 lines like:目前,文本文件由 5 行组成,例如:
0.116 0.116
0.118 0.118
0.12 0.12
0.122 0.122
0.124 0.124
This is my code:这是我的代码:
#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);
}
This only reads the first half of the file, which are the x values.这仅读取文件的前半部分,即 x 值。 Of which output is其中output为
0.116000 0.116000
0.118000 0.118000
0.120000 0.120000
0.122000 0.122000
The total number of inputs is 4输入总数为 4
However, I want to read a text file and store the values in two different arrays for x and y values.但是,我想读取一个文本文件并将值存储在两个不同的 arrays 中,用于 x 和 y 值。
The new text file will look like this新的文本文件将如下所示
0.116,-0.84009 0.116,-0.84009
0.118,4.862 0.118,4.862
0.12,-1.0977 0.12,-1.0977
0.122,0.22946 0.122,0.22946
0.124,3.3173 0.124,3.3173
How do i go changing my code above to recognize the Y values after "," sign?我如何 go 更改我上面的代码以识别“,”符号后的 Y 值? And to add both into two arrays at once?并同时将两者添加到两个 arrays 中?
I tried compiling your code posted on pastebin and received an error because of a missing bracket in your while statement.我尝试编译您在 pastebin 上发布的代码,但由于您的 while 语句中缺少括号而收到错误。 That's an easy fix.这很容易解决。 The larger issue is in the condition of the while loop.更大的问题在于 while 循环的条件。
fscanf
returns the number of input items converted and assigned on each call. fscanf
返回在每次调用中转换和分配的输入项的数量。
When you modified your code to return two
values, the condition in the while loop fscanf(inp, "%lf,%lf", &v1,&v2) == 1
would fail and the loop will not be entered.当您修改代码以返回two
值时,while 循环fscanf(inp, "%lf,%lf", &v1,&v2) == 1
中的条件将失败并且不会进入循环。
Please modify the while statement to ( have included the missing "(" too )..请将 while 语句修改为 (也包含缺少的 "(" )..
while ( (fscanf(inp, "%lf, %lf", &v1, &v2) == 2) && (!feof(inp)) )
and you should be good to go!!! while ( (fscanf(inp, "%lf, %lf", &v1, &v2) == 2) && (!feof(inp)) )
你应该好好去!
In addition it would be a good practice to include the return type of int
for the main
function.此外,最好main
function 包含int
的返回类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.