所以这是一种菜单的一部分,唯一的问题是这个词没有进入数组" frase“,我已经尝试过用frase=”单词“,但是要知道为什么它不能工作。
if(lvl==1)
{
printf("lvl 1\n");
if (opc==1)
{
printf("Animales\n");
a = rand() %3 + 1;
printf("%d", a);
if (a=1)
frase <= "pato";
if (a=2)
frase <="ganso";
if (a=3)
frase <= "avispa";
}
if (opc==2)
{
printf("comida\n");
a = rand() %3 + 1;
if (a=1)
frase <="pasta";
if (a=2)
frase <="pizza";
if (a=3)
frase <="pastel";
}
if (opc==3)
{
printf("paises\n");
a = rand() %3 + 1;
if (a=1)
frase <="peru";
if (a=2)
frase <="brasil";
if (a=3)
frase <="egipto";
}
}`
发布于 2022-08-18 04:56:58
我建议你通过建模数据来解决这个问题。在本例中,使用了一个结构数组。然后进行索引以获得相关数据:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main() {
struct {
const char *opc;
const char **frase;
} data[] = {
{"Animales", (const char *[]) { "pato", "ganso", "avispa" }},
{"comida", (const char *[]) { "pasta", "pizza", "pastel" }},
{"paises", (const char *[]) { "peru", "brasil", "egipto" }}
};
srand(time(0));
int opc = rand() % 3;
printf("lvl 1 %s %s\n", data[opc].opc, data[opc].frase[rand() % 3]);
return 0;
}如果您有大量的数据,那么将数据放入一个文件中,并编写一个函数来在启动时构建结构。这种方法的一个特殊情况是将数据存储在像SQLite这样的轻量级数据库中,然后您可以在运行时查询相关数据,或者在启动时加载所有数据。
您很多人不再需要复制frase,但是如果您想使用strcpy:
char frase[100];
strcpy(frase, data[opc].frase[rand() % 3]);发布于 2022-08-18 04:37:19
代码中需要改进的内容有多个。应该将if(a=1)更改为==。不确定您所说的frase<="pato"、strcpy或strncpy是什么意思。请参考以下示例代码。
void copytoarray(char *array, char *word, unsigned int len)
{
if(array == NULL || word == NULL)
{
return;
}
strncpy(array, word, len);
}
int main(void) {
char frase[15] = {'\0'};
int a, lvl =1;
int opc =1;
if(lvl==1)
{
printf("lvl 1\n");
if (opc==1)
{
printf("Animales\n");
a = rand() %3 + 1;
printf("%d\n", a);
if (a==1)
copytoarray(frase, "pato", strlen("pato"));
if (a==2)
copytoarray(frase, "ganso", strlen("ganso"));
if (a==3)
copytoarray(frase, "avispa", strlen("avispa"));
}
}
printf("Word: %s\n ",frase);
}https://stackoverflow.com/questions/73397340
复制相似问题