【问题标题】:How to substitute variables names in C如何在 C 中替换变量名称
【发布时间】:2016-04-13 09:35:47
【问题描述】:
#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 中生成随机密码而编写的代码。

我想用strcpy(motindex, secret); 替换index。我该怎么做?

【问题讨论】:

  • 将单词放入一个指针数组中。然后索引到数组中以选择所需的单词。
  • 指针数组?你能更精确一点吗?
  • 使用char *arr[] = {"word1", "word2", ...};
  • 作为旁注,如果您记住,变量名称是编译时的东西,一旦二进制文件存在,就不存在变量名称,因此,也许会有所帮助。

标签: c string random strcpy


【解决方案1】:

你不能;字符串不是标识符,标识符也不是字符串。
(变量名甚至不存在于程序中——它们只存在于源代码中。)

使用数组并将索引用作“名称”。

我还怀疑你想反过来复制秘密,所以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;
}

【讨论】:

  • 好的,这就是为什么,我在 strcpy 函数中颠倒了一些东西。感谢您指出了这一点。结果给了我很好的答案。只剩下一个问题:为什么要使用双向阵列?为什么是 128?
  • @Gradiuss 我已经编辑了代码以匹配我相信你所追求的。 (如果你想修改字符串,这两个维度是必要的,而 128 是完全任意的“2 的幂,有足够的空间”。)
【解决方案2】:

我认为二维数组可以解决你的问题 下面的代码列表

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define SC_NUM  10
int main(){
    const char motSecret[SC_NUM][100] = {
        "POMME",
        "POIRE",
        "PASTEQUE",
        "MELON",
       //some more const secret
    };

    int index = ((rand() % SC_NUM) + SC_NUM) % SC_NUM;
    char secret[100];
    strcpy(secret, motSecret[index]);
    printf("Secret is now %s\n", secret);
   return 0;
}

【讨论】:

  • ((rand() % SC_NUM) + SC_NUM) % SC_NUM 等价于rand() % SC_NUM
  • 感谢您的帮助,不幸的是,秘密始终是MELON(最后一个)。所以也许你的随机函数没有优化。
  • @Gradiuss Google srand.
  • @molbdnilo,你是对的。我以为 rand 可能返回负数,但我阅读了 rand 手册页(cplusplus.com/reference/cstdlib/rand/?kw=rand),发现它返回的值介于 0 和 RAND_MAX 之间。
  • @Gradiuss 你可以添加代码srand(time(NULL)); 随机兰特的种子。
猜你喜欢
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 2013-06-19
  • 2020-03-23
  • 2013-06-20
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
相关资源
最近更新 更多