簡體   English   中英

我如何在 C 中導入和導出超過 1 個數字 in.txt

[英]how can i import and export more than 1 number in .txt in C

第一個程序,我輸入 a, b,c,d,e

#include"stdio.h"
#include"stdlib.h"

int main(){
    FILE *f;
    f = fopen("abcde","w");
    if(f==NULL){
        printf("Error");
        exit(0);
    }
    float a,b,c,d,e;
    a=5;
    b=6;
    c=7;
    d=8;
    e=9;
    fprintf(f,"%f",a);
    fprintf(f,"%f",b);
    fprintf(f,"%f",c);
    fprintf(f,"%f",d);
    fprintf(f,"%f",e);
    fprintf(f,"%f",f);
    fclose(f);
}

然后是第二個程序,我想要 output a,b,c,d,e。 但它只是 output 一個。 我怎么能 output 所有 a, b, c,d,e

#include"stdio.h"
#include"stdlib.h"

int main(){
    FILE *f;
    f = fopen("abcde","r");
    if(f==NULL){
        printf("Error");
        exit(0);
    }
    float a,b,c,d,e;
    fscanf(f,"%f",&a);
    fscanf(f,"%f",&b);
    fscanf(f,"%f",&c);
    fscanf(f,"%f",&d);
    fscanf(f,"%f",&e);
    printf("%f  %f  %f  %f  %f",a,b,c,d,e);
    fclose(f);
}

你可以看看我的img。 在 txt 文件中它包含所有數據在此處輸入圖像描述

非常感謝你,

當您寫入文件時,沒有任何東西可以分隔每個數字。 因此,當它讀取一個float時,它會在到達第二個小數點時停止。

寫入文件時,在每個數字之間放置一個空格或換行符:

fprintf(f,"%f ",a);
fprintf(f,"%f ",b);
fprintf(f,"%f ",c);
fprintf(f,"%f ",d);
fprintf(f,"%f ",e);
fprintf(f,"%f ",f);

然后,當您重新讀取數字時,該空格充當分隔符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM