c - 如何从文本文件中读取数据并将其存储在 C 语言的变量中?
问题描述
我正在尝试读取 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]);
推荐阅读
- python-3.x - 如何在python中将数据帧拆分为相等数量的子集
- android - 以编程方式添加布局+子项
- webpack - webpack mini-css-extract-plugin => 在单个条目上输出多个 css 文件
- python - 遍历数据框并根据字典条件进行更新
- android - 类型不匹配:推断类型是 GoogleSignInAccount?但应使用 GoogleSignInAccount > 任务:app:buildInfoGeneratorFdroidDebug
- python-3.x - 如何解析yaml列表中的嵌套字典?
- mysql - 使用 WooCommerce 的“on 子句”SQL 查询中的未知列“O.order_id”
- java - 带有 Java 11 的 SoapUI maven 插件
- java - Spring H2 数据库 EmbeddedDatabaseFactory 错误的连接 URL
- android - Fused Location Provider - 获得高精度