简体   繁体   中英

Using fscanf to store in array

for a school project I need to open a .txt file and copy the information on to a multidimensional array, but I'm having trouble copying the content. The file is a 52 card deck:

4O 7E AC 3E 4E TO 4C 8P 5O TE 6O 8E AP
5E 6P JO 7C 7O QO 8O 3O 2E 9C 5P TC 6C
5C 8C 9O 6E 9E KO 2P 9P QP KE 3P 4P JE 
7P 2C AO JC QE TP 2O JP 3C QC KC AE KP 

As I said, I need to store sets o 5 cards in a multidimensional array, in a total of 10 sets [52/5=10] (if a set is incomplete (=not enough cards) we're supposed to ignore the leftovers). So far I have this

void card_store(char *argv[]) { 
char cards_set[10][5][3];
FILE* fp = fopen("deck.txt", "r");
char str;
int i,j;

str = fgetc(fp);  //Here I'm using fgetc but I want fscanf (don't know how)

    while (str != EOF)
    {
        for (i = 0; i < 10; i++) {
            for (j = 0; j < 5; j++) {
                 cards_set[i][j] = str;
            }
        }
    }

}

For example: cards_set[0] = {4O,7E,AC,3E,4E}

Just like scanf , you use fscanf , with extra parameter fp as first parameter. More about fscanf here .

So, for your problem, you can use fscanf :

char card_number, card_type;

while (fscanf(" %c%c", &card_number, &card_type) == 2)  // while there is input in file
{
    // do processing here
}

or if you know the exact length of the data, you can use a for loop, with the same logic.

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