【问题标题】:Return value from string function字符串函数的返回值
【发布时间】:2016-08-26 08:38:54
【问题描述】:

我有一个包含 20 个单词的字符串数组。我做了一个从数组中取出 1 个随机单词的函数。但我想知道如何从数组中返回该单词。现在我正在使用 void 函数,我使用了 char 类型,但它不会工作。这里有一点帮助?需要制作猜词游戏。

代码:

#include <iostream>
#include <time.h>
#include <cstdlib>
#include <stdlib.h>
#include <algorithm>///lai izmantotu random shuffle funckiju
#include <string>
using namespace std;


void random(string names[]);


int main() {
     char a;
     string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
                       "kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
                       "saule", "parks", "svece", "diegs", "migla", "virve"};

random(names);

        cout<<"VARDU MINESANAS SPELE"<<endl;
        cin>>a;







return 0;
}

void random(string names[]){
    int randNum;
for (int i = 0; i < 20; i++) { /// makes this program iterate 20 times; giving you 20 random names.
srand( time(NULL) ); /// seed for the random number generator.
randNum = rand() % 20 + 1; /// gets a random number between 1, and 20.
names[i] = names[randNum];
}
//for (int i = 0; i < 1; i++) {
//cout << names[i] << endl; /// outputs one name.
//}

}

【问题讨论】:

  • 我看不出您发布的代码与您所要求的内容有何关联(这不是很清楚,TBH)。
  • 要么使用vector&lt;string&gt;,要么告诉函数数组中有多少元素。不要将 20 硬编码到函数中。这与您的问题无关,但相关的一般建议。确保函数知道它们正在处理的数组有多大。
  • 返回一个字符串呢? std::string random(std::string names[]);
  • 请参阅 srand() — Why call it only once?,详细了解为什么您使用 srand() 会被彻底误导。
  • 也永远不要在循环中播种随机数生成器,在程序开始时播种 一次

标签: c++ arrays string function void


【解决方案1】:

我对字符串不是很熟悉,但你应该可以将 random() 声明为字符串函数。

例如: 字符串随机(字符串名称[]);

【讨论】:

    【解决方案2】:

    使random 返回string。您还只需为数字生成器播种一次。由于您只想从数组中获取 1 个随机单词,因此不需要 for 循环。

    string random(string names[]){
        int randNum = 0;
        randNum = rand() % 20 + 1;
        return names[randNum];
    }
    

    然后,在main 函数中,将string 变量赋值给random 函数的返回值。

    int main() {
        srand( time(NULL) ); // seed number generator once
        char a;
        string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
                           "kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
                           "saule", "parks", "svece", "diegs", "migla", "virve"};
    
        string randomWord = random(names);
    
        cout<<"VARDU MINESANAS SPELE"<<endl;
        cin>>a;
    
        return 0;
    }
    

    【讨论】:

      【解决方案3】:

      另外 srand(time(NULL)) 应该只被调用一次,在 main() 函数的开头。

      【讨论】:

      • 而且你不应该在现代代码中使用srand()。而是看&lt;random&gt;
      【解决方案4】:

      在您的问题以及上一个答案中,您正在超出访问名称数组的范围:

      int randNum = rand() % 20 + 1;
      return names[randNum];
      

      您从不访问名称[0],而是在寻址名称[20]时到达数组后面。

      【讨论】:

        猜你喜欢
        • 2011-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多