gpt4 book ai didi

无法从文件中读取单个 double 值 (C)

转载 作者:行者123 更新时间:2023-11-30 17:02:13 25 4
gpt4 key购买 nike

我无法从文件中读取单个数据点。它应该能够读取两列数据(例如 x 和 y 值),但我发现我的代码甚至无法读取单个 double 值。任何帮助,将不胜感激。

该文件位于D:\test.txt并且有一个值 1.11111

Enter the location of file (text file) of the airfoil coordinates: D:\test.txt There are 1 lines The amount of data in x and y is 1 points and 1 points. failed to read. * Process returned 1 * Press any key to continue...

这是我的意见。

/*
Purpose:
Create a program that can take in a list of data points that represents an airfoil from some file.
Then through the use of spline function, spline the data points for interpolation then go on to plotting them.
With these data points, use the Vortex Panel Method to obtain coefficients of lift, pressure, and tangential velocity.
Then after these are calculated, plot each with respect to the splined x data points.
*/

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <stdlib.h>
#define LEN 12

int countlines(FILE *fp);

int main (void)
{
char airfoil[500];
double *x_data = NULL;
double *y_data = NULL;
FILE *pfile = NULL;
int line_count = 0;
double test = 0.0;


printf("Enter the location of file (text file) of the airfoil coordinates: ");
scanf("%s", airfoil);

if(fopen_s(&pfile, airfoil, "r"))
{
printf("Error opening the file for reading the data. Program terminated.\n");
exit(1);
}

line_count = countlines(pfile);

printf("There are %d lines\n", line_count);

x_data = realloc(x_data, line_count*(sizeof(double)));
y_data = realloc(y_data, line_count*(sizeof(double)));

if((!x_data) || (!y_data))
{
printf("Memory allocation has failed. Exiting...\n");
exit(1);
}

printf("The amount of data in x and y is %zu points and %zu points.\n", (sizeof(x_data)/sizeof(double)), (sizeof(y_data)/sizeof(double)));

if(EOF == fscanf_s(pfile, "%lf", &test))
{
printf("failed to read.\n");
exit(1);
}
//for(int i = 0; i < line_count; i++)
//{
//fscanf(pfile, " %lf", &x_data[i]);
//}

printf("The x-data are %lf!\n", test);
//for(int i = 0; i < line_count; i++)
//{
//printf("%.2lf", x_data[i]);
//printf("\n");
//}

return 0;
}

int countlines(FILE *fp)
{
int lines = 0;
char str[LEN];
while(!feof(fp))
{
if (fgets(str, LEN, fp) != NULL);
{
lines++;
}
}

return lines;
}

最佳答案

countlines 只是将文件指针带到文件末尾。在读取任何内容之前,必须先将文件倒回到开头:

fseek(pfile,0,SEEK_SET);

您可以在 countlines() 中执行此操作。

另请参阅评论,发现更多错误。

关于无法从文件中读取单个 double 值 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36667448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com