c - C语言中如何替换变量名

标签 c string random strcpy

#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/

相关文章:

r - 从字符串中提取数字,如果它后跟 R 中的某些字符

c - select 等待在套接字中写入的奇怪行为

谁能给我解释一下这段代码吗?我是 C 新手

c - 发送 ptrace 信号后获取僵尸进程

python - CSPRNG Python 2.7 实现

mysql - 如何在 MySQL 中随机连接表?

php - 兰德();排除并已经随机生成的数字..?

c - 字符串数组中不同出现的次数

c - 如何从字符串中获取字符

string - Go channel 将每个字母作为字符串而不是整个字符串