首页 > 解决方案 > 如何从文本文件中读取数据并将其存储在 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 的值与上面给出的数据不匹配。

代码输出

请帮我解决这个问题。

标签: c

解决方案


junk1并且junk2应该是能够存储字符串的 char 数组。

但是由于它是垃圾,您不能通过*fscanf转换说明符中使用将其存储在任何地方:

fscanf(file, "%*s %*s %lf\n", &Data[i]);

fscanf文档: https ://en.cppreference.com/w/c/io/fscanf


推荐阅读