Return 来自字符串函数的值

Return value from string function

我有一个包含 20 个单词的字符串数组。我做了一个函数,从数组中取 1 个随机单词。但我想知道我如何 return 数组中的那个词。现在我正在使用 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.
//}

}

我不是很熟悉字符串,但您应该能够将 random() 声明为字符串函数。

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

制作randomreturnstring。您也只需要为数字生成器播种一次。由于您只想从数组中获取 1 个随机单词,因此不需要 for 循环。

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

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

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;
}

此外,srand(time(NULL)) 只能在 main() 函数的开头调用一次。

在您的问题和之前的回答中,您 运行 越界访问名称数组:

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

您永远不会访问 names[0],而是在寻址 names[20] 时到达数组后面。