【问题标题】:Random string from an array in c来自c中数组的随机字符串
【发布时间】:2011-01-04 12:36:15
【问题描述】:

我对 C 语言有点陌生,但对编程并不陌生。我正在尝试创建一个程序,该程序接受输入并使用已保存在数组中的随机字符串进行回复(例如)。

我不是想创建一个随机字符串,我希望它们是“固定的”,就像在 Java 中一样:

String [] sa; 
sa[0] = "Hello, World"; 
sa[1] = "Hi dude!";

【问题讨论】:

  • 您是否有一个程序可以一直接受输入并以“随机”固定字符串回复?
  • 是的,我的问题是硬编码我的答案并随机化它
  • printf("%s\n", sa[rand() % 2]);

标签: c arrays random


【解决方案1】:
const char *sa[]={"Hello, World","Hi dude!"};

那你就可以了

return sa[i];

返回值为char *
只需确保 i 在界限内

【讨论】:

  • const char *sa[] 会更好。
【解决方案2】:
#include <stdio.h>
#include <stdlib.h>

int main() {
    const char *messages[] = {
        "Hello!",
        "How are you?",
        "Good stuff!"
    };
    const size_t messages_count = sizeof(messages) / sizeof(messages[0]);
    char input[64];
    while (1) {
        scanf("%63s", input);
        printf("%s\n", messages[rand() % messages_count]);
    }
    return 0;
}

【讨论】:

    【解决方案3】:

    不清楚您到底想要什么,但这里简要描述了字符串在 C 中的工作原理。

    C 中没有像 Java 中那样的 String 数据类型。您必须使用字符数组。对于字符串数组,您必须使用二维字符数组。

    char myStrings[MAX_NUMBER_OF_STRING][MAX_LENGTH_OF_STRING];
    

    【讨论】:

      【解决方案4】:

      这里是你要找的东西:

      #include <stdio.h>
      #include <stdlib.h>
      
      int main(int argc, char** argv)
      {
          char buffer[42];
          const char *mytext[] = {"A1", "A2", "A3"};
          scanf("%41s", buffer);
          srand(time(NULL));
          printf("Random text: %s\n", mytext[rand() % (sizeof(mytext) / sizeof(mytext[0]))]);
          return 0;
      }
      

      【讨论】:

        【解决方案5】:

        #include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; int main(){ char str[7][100]={"hello1","hello2","hello3","hello4","hello5","hello6","hello7"}; printf("%s",str[rand()%7]); return 0; }

        【讨论】:

        • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
        猜你喜欢
        • 2020-01-12
        • 1970-01-01
        • 2015-09-08
        • 1970-01-01
        • 2021-12-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-12
        • 1970-01-01
        相关资源
        最近更新 更多