简体   繁体   English

如何从 c 中的 .txt 文件中读取一行数字?

[英]How can I read a row of numbers from a .txt file in c?

I'm trying to make a code that will read three numbers (13.1, 270.66, and 81.3) from the first row of a .txt file and associate them with the variables I want it to.我正在尝试编写一个代码,该代码将从 .txt 文件的第一行读取三个数字(13.1、270.66 和 81.3),并将它们与我想要的变量相关联。 This is what I tried:这是我尝试过的:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    char filename[100];
    printf("Enter the name (including file extension) of the file you wish to use the values from: ");
    scanf("%s",filename);
    FILE *filepointer=fopen(filename,"r");
    if (filepointer==NULL){
        printf("Error: Couldn't open file: %s",filename);
    }
    double value1;
    double value2;
    double value3;
    rewind(filepointer);
    fscanf(filepointer,"%g %g %g",&value1,&value2,&value3);
    printf("Your values are: %g %g %g",value1,value2,value3);
    fclose(filepointer);
}

FYI in the .txt file the values are set us like this:13.1 270.66 81.3仅供参考,在 .txt 文件中,值是这样设置的:13.1 270.66 81.3

%g in scanf() is for reading float . scanf() %g用于读取float You should use %lg to read double instead.您应该使用%lg来读取double

Also you should:你还应该:

  • Stop executing rest of the program when fopen() failed.fopen()失败时停止执行程序的其余部分。
  • Check the return values of scanf() and fscanf() to check if they succeeded to read all requested things.检查scanf()fscanf()的返回值以检查它们是否成功读取了所有请求的内容。
  • Specify the maximum number of characters for %s (at most the size of destination minus one for terminating null-character) to prevent buffer overrun.指定%s的最大字符数(最多为目标大小减去一用于终止空字符)以防止缓冲区溢出。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
    char filename[100];
    printf("Enter the name (including file extension) of the file you wish to use the values from: ");
    if (scanf("%99s",filename) != 1){ /* specify the maximum length and check the result */
        puts("Error: failed to read file name");
        return 1;
    }
    FILE *filepointer=fopen(filename,"r");
    if (filepointer==NULL){
        printf("Error: Couldn't open file: %s",filename);
        return 1; /* stop execution when fopen() fails */
    }
    double value1;
    double value2;
    double value3;
    rewind(filepointer);
    /* use correct format specifier and check the result */
    if (fscanf(filepointer,"%lg %lg %lg",&value1,&value2,&value3) == 3){
        printf("Your values are: %g %g %g",value1,value2,value3);
    } else {
        puts("Error: failed to read numbers");
        fclose(filepointer);
        return 1;
    }
    fclose(filepointer);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM