gpt4 book ai didi

c++ - 字符串函数的返回值

转载 作者:太空宇宙 更新时间:2023-11-04 16:05:01 24 4
gpt4 key购买 nike

我有一个包含 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.
//}

}

最佳答案

使随机返回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;
}

关于c++ - 字符串函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36967907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com