我试图读取C中的文本文件。该文件的名称为test.txt,并且具有以下格式。
Nx = 2
Ny = 4
T = 10
我已经编写了此C代码来读取Nx,Ny和T的值,分别为2、4和10。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
double Data[3]; // I'm interested in this information
char junk1, junk2; // junk variables to avoid first two characters
FILE * file = fopen("test.txt", "r"); // open file
for(int i = 0; i < 3; i++) // each loop will read new line of file; i<3 for 3 lines in file
{
fscanf(file, "%s %s %lf\n", &junk1, &junk2, &Data[i]); //store info in Data array
printf("%f\n", Data[i]); // print Data, just to check
}
fclose(file);
int Nx; // store data in respective variables
int Ny;
double T;
Nx = Data[0];
Ny = Data[1];
T = Data[2];
printf("Value of Nx is %d\n", Nx); // Print values to check
printf("Value of Ny is %d\n", Ny);
printf("Value of T is %f\n", T);
}
但是得到这个作为输出。此输出错误,因为Nx,Ny和T的值与上面给出的数据不匹配。
请帮我解决这个问题。
junk1
并且junk2
应该是char数组,以便能够存储字符串。
但是由于它是垃圾,因此您不能通过*
在fscanf
转换说明符中使用将其存储在任何地方:
fscanf(file, "%*s %*s %lf\n", &Data[i]);
fscanf
说明文件:https : //en.cppreference.com/w/c/io/fscanf
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句