About loading and writing C language files

Asked 1 years ago, Updated 1 years ago, 348 views

I'd like to write down the results of the rock-paper-scissors match (number of wins, number of losses, number of draws) in a file and read the total, but the total number of wins will be output, and the number of draws will be initialized for each game.
 I have already written the results of each match in a file, so I would like to print out the total number of matches I have played so far.

If anyone knows how to write correctly, please let me know.Thank you for your cooperation.

#include<stdio.h>
# include <time.h>
# include <stdlib.h>
# include "jankendata.txt"

int main (void)
{   
    int win = 0, loss = 0, draw = 0;
    int wsum = 0, lsum = 0, dsum = 0;
    FILE*fp;
    if(((fp=fopen("jankendata.txt", "r"))==NULL){
        printf("Failed to open file.\n";
    } else{
        while(fscanf(fp, "%d%d%d", & win, & loss, & draw)!=EOF)
        wsum=wsum+win;
        lsum = lsum + loss;
        dsum = dsum + draw;
        printf("%d wins %d losses %d draws \n", wsum, lsum, dsum);
        fclose(fp);
    }
    
    // Choose the way you want to make it
    int me, npc, result;
    printf("Choose your hand ->\n[Goo]:0[Choki]:1[par]:2 End:3\n";
    scanf("%d", & me);

    if(me==0||me==1||me==2){
        sland(time(NULL)));
        npc = land()%3;
        printf("The opponent got %d!\n", npc);    
    } else if(me==3){
        printf("Finish.\n");
        exit(0);
    } 

        
     result=(me-npc+3)%3;
    
    int w = 0, l = 0, d = 0;
    if(result==2){
        printf("Your Victory\n");
        w++;
    } else if(result==1){
        printf("Your Losing\n");
        l++;
    } else if(result==0){
        printf("Draw\n");
        d++;
    }

    if(((fp=fopen("jankendata.txt", "a+"))==NULL){
        printf("Failed to open file.\n");
    } else{
        fprintf(fp, "%d%d%d\n", w, l, d);
        fclose(fp);
    }

    return EXIT_SUCCESS;
}

c

2022-09-30 22:00

1 Answers

The problem is that the while statement is not enclosed.

while(fscanf(fp, "%d%d%d", & win, & loss, & draw)!=EOF){
    wsum=wsum+win;
    lsum = lsum + loss;
    dsum = dsum + draw;
}

#include "jankendata.txt" is not required.

#include does not describe the file to be used, but rather the program file to be used.


2022-09-30 22:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.