arrays - 将文件中包含的字符串保存在字符串数组中,我不是数组的最佳格式
问题描述
代码应该读取一个这种类型的文件,其中包含一系列的石头,剪刀布匹配,通过 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;
}
解决方案
推荐阅读
- python - 如何在 if else 条件下循环函数
- python - TypeError: __add__() 缺少 1 个必需的位置参数:
- xslt - 如何限制 XSLT 中的字数?
- automated-tests - Specflow 使用带有示例表的背景?
- azure - Azure VPN 登录在没有 MFA 的情况下发生
- c# - 文本文件中的空格显示为“?” 在 C# 中
- r - R:如何计算一个有长度条件的纵向数据库中连续出现的次数?
- c# - ExecuteSqlCommand 在@p0 附近抛出不正确的语法,但在 ssms 中它成功执行
- reactjs - React 循环遍历状态变量在渲染最终值之前所具有的每个值
- javascript - 针对多个条件改进我的数组搜索