繁体   English   中英

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

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

我正在尝试编写一个代码,该代码将从 .txt 文件的第一行读取三个数字(13.1、270.66 和 81.3),并将它们与我想要的变量相关联。 这是我尝试过的:

#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);
}

仅供参考,在 .txt 文件中,值是这样设置的:13.1 270.66 81.3

scanf() %g用于读取float 您应该使用%lg来读取double

你还应该:

  • fopen()失败时停止执行程序的其余部分。
  • 检查scanf()fscanf()的返回值以检查它们是否成功读取了所有请求的内容。
  • 指定%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