#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main()
{
const char mot1[] = "POMME", mot2[] = "POIRE", mot4[] = "PASTEQUE", mot5[] = "MELON", mot6[] = "ORANGE", mot7[] = "FRAISE", mot8[] = "FRAMBOISE", mot9[] = "CITRON", mot10[] = "MANGUE";
srand(time(NULL));
int index = rand() % 10 + 1;
char secret[100] = "";
strcpy(motindex, secret);
printf("Secret is now %s\n", secret);
return 0;
}
这是我编写的代码,用于从一系列 const char 中生成随机 secret 单词。
我想替换 strcpy(motindex, Secret);
中的 index
。我怎样才能做到这一点?
最佳答案
你不能;字符串不是标识符,标识符也不是字符串。
(变量名称甚至不存在于程序中 - 它们仅存在于源代码中。)
使用数组并使用索引作为“名称”。
我还怀疑您想以相反的方式复制 secret ,因此 secret
包含水果的名称。
int main()
{
const char* mot[]= {"POMME", "POIRE", "PASTEQUE", "MELON", "ORANGE", "FRAISE", "FRAMBOISE", "CITRON", "MANGUE"};
srand(time(NULL));
int index = rand() % 9; /* You only have nine strings... */
char secret[100] = "";
strcpy(secret, mot[index]);
printf("Secret is now %s\n", secret);
return 0;
}
关于c - C语言中如何替换变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36594344/