【发布时间】: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<string>,要么告诉函数数组中有多少元素。不要将 20 硬编码到函数中。这与您的问题无关,但相关的一般建议。确保函数知道它们正在处理的数组有多大。 -
返回一个字符串呢?
std::string random(std::string names[]); -
请参阅
srand()— Why call it only once?,详细了解为什么您使用srand()会被彻底误导。 -
也永远不要在循环中播种随机数生成器,在程序开始时播种 一次。
标签: c++ arrays string function void