简体   繁体   中英

How to read integers from a specific point of a .txt file using C?

I need to implement a game using the C language where a functionality is to able the player to save the game to play later. A requirement is to save the data of the game on a .txt file in the next way: 1) the number of players in the first row; 2) the cards on the table in the second row, identified by player 0 and the existent cards. 3) the next information for each player: number of player, if it is a real player or bot (1 if it's bot, 0 if it's real), the name of the player, the points and the cards in the hand. See the example below of the format of how I need to store the data on the .txt file:

2\n
0:T;23,43,45\n
1:0;John;23:12,32,44,43\n
2:1;BOT1;34:43,54,53,45\n
EOF

Now, I don't have any idea of how to store, for example the cards of player 1 (named John) in a structure player[0].cards[7], when the player is loading the game after this .txt file. How can i save the name of player 1 (John) into player[0].name and then save the name of the second player (BOT1) into player[1].name.

I've been trying to solve this for days, but I'm not being successful. Can someone help me to understand how to store a specific number/string from a specific position on a .txt file back into my code? How can I make my code read the numbers, for example 12,32,44,43 and store it the proper array. How can I make my code navigate the file with all the lines, the ":", ";" and ",".

I'm not asking for the solution. I'm just want someone to enlight my mind so that I can find the proper way to do this. Any help is welcome. Thank you.

Assume that you use fgets to read the file line by line; Then you can parse each line and each part of such a line separately. As far as the list of numbers is concerned, you could use strrchr to find the position of the last colon, and then use strtok to split the comma separated values one by one. Hope it helps.

int main() {

    char aSingleLine[] = "1:0;John;23:12,32,44,43\n";
    char* lastColon = strrchr(aSingleLine,':');
    if (lastColon) {
        char* numbers = lastColon+1; // one after the last colon;
        int i=0;
        char *numStr = strtok(numbers,",");
        while(numStr != NULL) {
            int numVal;
            if (sscanf(numStr,"%d",&numVal)==1) {
                printf("%dth value: %d\n", i, numVal);
            }
            else {
                printf("invalid number: %s",numStr);
            }
            i++;
            numStr = strtok(NULL,",");
        }
    }
}

Output:

0th value: 12
1th value: 32
2th value: 44
3th value: 43

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM