首页 > 解决方案 > 将文件中包含的字符串保存在字符串数组中,我不是数组的最佳格式

问题描述

代码应该读取一个这种类型的文件,其中包含一系列的石头,剪刀布匹配,通过 read_file 函数然后返回包含文件中所有信息的数组

纸岩

剪刀摇滚

摇滚剪刀

剪纸

剪刀摇滚

摇滚剪刀

我不知道应该如何为这个任务实际定义一个合适的数组以及我应该如何 sscanf 进入它

然后我需要将文件中的所有单词传递给一个函数,然后将字符串转换为数字,例如rock应该变成1(这是为了让它们之间的比较更容易以后)

#include  <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CHAR_MOVE 8

#define rock 1
#define paper 2
#define scizor 3






int figure_code(char *name)
{
    if (strcmp(name, "rock") == 0)
        {
            return 1;
        }
        if (strcmp(name, "paper") == 0)
        {
            return 2;
        }
        if (strcmp(name, "scizor") == 0)
        {
            return 3;
        }
        return -1;
}



char *Read_File(FILE *infile, int *n)
{
    int i;
    int dim = 4;
    char buf[1000];
    char p[dim][MAX_CHAR_MOVE];
    char *list;
    list  = &p[0][0];







    while (fgets(buf,sizeof(buf), infile) != NULL )
    {
        sscanf(buf, "%s %s", *(list[*n]), *(list[*n+1]));
        *n = *n+2;
        if (*n>= dim)
            {
            dim = dim*2;
            list = realloc (list,  sizeof(*list) * dim);
            }

     }


        return list;
}



void print_everything(char *list, int n)
{
    int c;
    int z;
    for (c = 0;c<n; c++ ){
        printf("%s\n", list[c]);
    }
}





int main(int argc,const char *argv[])
{
FILE *f;
char *list[][];
int n;

if (!( argc != 3)){
    printf("wrong dimension\n");
    return -1;
}

f = fopen(argv[1], "r");

list = Read_File(f, &n);

print_everything(elenco, n);
fclose(f);

return 0;
}




标签: arraysc

解决方案


推荐阅读