簡體   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