簡體   English   中英

我不確定如何正確使用 fscanf

[英]I am unsure how to use fscanf properly

該程序應該輸入一個數字並計算學生分數之間的平均值。 該程序僅適用於以前的學生,但不適用於以下學生。 我認為 fscanf 有問題。 有人可以幫忙嗎?

int main ()
{
    FILE *cfPtr;
    int matricola_in, matricola, nEsami, codEsame, voto;
    char nome[20], cognome[20];
    int i, j, trovato = 0;
    float somma = 0.0;

    printf("Inserisci una matricola:\n");
    scanf("%d", &matricola_in);

    if( (cfPtr = fopen("studenti.txt", "r")) == NULL )
        printf("Errore");

    while( !feof(cfPtr) || trovato != 1 ){
        fscanf(cfPtr, "%d%s%s%d\n", &matricola, nome, cognome, &nEsami);
        if( matricola_in == matricola ){
            trovato = 1;
            for( i = 0; i < nEsami; i++ ){
                fscanf(cfPtr, "%d%d\n", &codEsame, &voto);
                somma += voto;
            }
            printf("Media: %.1f\n", somma/nEsami);
        }
    }

    fclose(cfPtr);

    return 0;
}

編輯:數據看起來像:

matricola nome cognome n.esami`<eol>`
(for n.esami-rows)codice esame voto`<eol>`
...

不清楚,但似乎該文件包含有四項或兩項的混合行。
考慮閱讀每一行。 使用 sscanf 將該行解析為最多四個字符串。 根據需要使用sscanf從行中捕獲整數。 如果有兩個項目,則在trovato標志指示已找到匹配項時處理它們。 如果有四個項目,查看是否有匹配項並設置trovato

int main ()
{
    FILE *cfPtr;
    int matricola_in, matricola, nEsami, codEsame, voto;
    char nome[20], cognome[20];
    char temp[4][20];
    char line[200];
    int result;
    int i, j, trovato = 0;
    float somma = 0.0;

    printf("Inserisci una matricola:\n");
    scanf("%d", &matricola_in);

    if( (cfPtr = fopen("studenti.txt", "r")) == NULL ) {
        printf("Errore");
        return 0;
    }

    while( fgets ( line, sizeof line, cfPtr)){//read a line until end of file
        result = sscanf ( line, "%19s%19s%19s%19s", temp[0], temp[1], temp[2], temp[3]);//scan up to four strings
        if ( result == 2) {//the line has two items
            if ( trovato) {// match was found
                sscanf ( temp[0], "%d", &codEsame);
                sscanf ( temp[1], "%d", &voto);
                somma += voto;
            }
        }
        if ( result == 4) {//the line has four items
            if ( trovato) {
                break;//there was a match so break
            }
            sscanf ( temp[0], "%d", &matricola);
            sscanf ( temp[3], "%d", &nEsami);
            if( matricola_in == matricola ){//see if there is a match
                trovato = 1;//set the flag
            }
        }
    }
    printf("Media: %.1f\n", somma/nEsami);//print results

    fclose(cfPtr);

    return 0;
}

暫無
暫無

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

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