简体   繁体   English

使用 fscanf 存储在数组中

[英]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.对于一个学校项目,我需要打开一个.txt文件并将信息复制到一个多维数组中,但是我在复制内容时遇到了麻烦。 The file is a 52 card deck:该文件是一副 52 张牌:

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).正如我所说,我需要将 5 张卡片存储在一个多维数组中,总共 10 个集合 [52/5=10](如果一组不完整(=没有足够的卡片),我们应该忽略剩余部分)。 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}例如: cards_set[0] = {4O,7E,AC,3E,4E}

Just like scanf , you use fscanf , with extra parameter fp as first parameter.就像scanf一样,您使用fscanf ,并将额外参数fp作为第一个参数。 More about fscanf here .更多关于fscanf 的信息

So, for your problem, you can use fscanf :因此,对于您的问题,您可以使用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.或者,如果您知道数据的确切长度,则可以使用for循环,具有相同的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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