[英]How to read data from a text file and store it in a variable in C language?
我正在嘗試讀取 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);
}
但是得到了這個 output。 這個 output 是錯誤的,因為 Nx、Ny 和 T 的值與上面給出的數據不匹配。
請幫我解決這個問題。
junk1
和junk2
應該是 char 的 arrays 才能存儲字符串。
但是由於它是垃圾文件,因此您不能通過在fscanf
轉換說明符中使用*
將其存儲在任何地方:
fscanf(file, "%*s %*s %lf\n", &Data[i]);
您的程序對輸入文件做出了強有力的假設:
"test.txt"
存在於當前目錄,可以讀取Nx
、 Ny
、 T
。它也有問題:
%s
的字符串讀入單個字符變量junk1
將導致未定義的行為,對於junk2
,因為fscanf()
將嘗試存儲字符串中的所有字符以及目標地址處的 null 終止符,從而覆蓋其他可能造成災難性后果的數據.main
有一個返回類型int
。這是一個更通用的方法:
#include <stdio.h>
#include <string.h>
int main() {
int Nx = 0, Ny = 0;
double T = 0;
int has_Nx = 0, has_Ny = 0, has_T = 0;
char buf[80];
FILE *file;
if ((file = fopen("test.txt", "r")) == NULL) {
fprintf(stderr, "cannot open test.txt\n");
return 1;
}
while (fgets(buf, sizeof buf, file)) {
if (buf[strspn(buf, " ")] == '\n') /* accept blank lines */
continue;
if (sscanf(buf, " Nx = %d", &Nx) == 1)
has_Nx = 1;
else
if (sscanf(buf, " Ny = %d", &Ny) == 1)
has_Ny = 1;
else
if (sscanf(buf, " T = %lf", &T) == 1)
has_T = 1;
else
fprintf(stderr, "invalid line: %s", buf);
}
fclose(file);
// Print values to check
if (has_Nx)
printf("Value of Nx is %d\n", Nx);
if (has_Ny)
printf("Value of Ny is %d\n", Ny);
if (has_T)
printf("Value of T is %g\n", T);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.