-1

このコードは、テキストファイルの最初の行のみを読み取ります。同じテキストファイルの複数の行を読み取るにはどうすればよいですか。ありがとうございました。
lnamefnameのGPAは88.0です
。lnamefnameのGPAは90.0です。

#include <stdio.h>
#include <stdlib.h>
struct stud{
char fname[21];
char lname[21];
float gpa;
} str;

int getStudData(struct stud *current_ptr); // struct function format 

int main(void){
struct stud str;
getStudData(&str);

printf("Last Name: %s\n First Name: %s\n GPA: %.2f\n"
    , str.fname, str.lname, str.gpa);
return 0;
}

int getStudData(struct stud *current_ptr){

FILE *studFile; // declaring a pointer file variable

studFile = fopen("StudData.txt", "r"); // format for fopen; file-variable = fopen(file_name, mode);

if ( studFile == NULL){ 
    printf("Error: Unable to open StudData.txt file\n"); //test for error
}
else {
    fscanf(studFile, "%20s %20s has a GPA of %f\n"
        , current_ptr->fname, current_ptr->lname, &current_ptr->gpa);
    // fscanf(file, format, &parameter-1, ...) 

    fclose(studFile); // The function fclose will close the file. 
}
return 0;
}
4

1 に答える 1

0

入力ファイルから複数の行を読み取るには、通常、行末 (EOL) 文字を指定するのが一般的です。ほとんどの場合、これは改行文字 ('\n') であり、入力ファイルからの読み取りはループとして設定されます。行の読み取り、停止、行の読み取り、停止、および繰り返しが必要な場合を除き、ループ構造を作成して、ファイルの終わり (EOF) になるまでファイルを 1 行ずつ読み取ることができます。到達しました。

以下のコードは、1 行だけを読み取り、ファイルを閉じます。

fscanf(studFile, "%20s %20s has a GPA of %f\n"
        , current_ptr->fname, current_ptr->lname, &current_ptr->gpa);
    // fscanf(file, format, &parameter-1, ...) 

    fclose(studFile); // The function fclose will close the file
于 2013-03-17T18:47:44.633 に答える