【发布时间】:2015-09-08 02:32:24
【问题描述】:
在我的小型 Qt 应用程序中,我想在单击按钮后从数组中选择一个随机字符串。我已经阅读了很多主题,但对我没有任何帮助。
所以在我的插槽中有一个包含多个字符串的数组。我还实现了<string>, <time.h> 和 srand。
#include "smashrandom.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
SmashRandom::SmashRandom(QWidget *parent)
: QWidget(parent)
{
// shortened version
connect(button, SIGNAL(clicked()), this, SLOT(Randomizer()));
}
void SmashRandom::Randomizer()
{
srand((unsigned int)time(NULL));
std::string characters[6] = {"Mario", "Luigi", "Peach", "Yoshi", "Pac Man", "Sonic"};
}
但是我如何从我的数组“字符”中随机选择一个字符串?通常我将 rand()% 用于 int 或 double 数组,但在这种情况下,我不知道如何将它用于随机字符串。
除此之外,可以从数组内的一个区域中选择一个随机字符串吗?例如,我只想要一个从 Mario 到 Yoshi 的随机字符串,这样 Pac Man 和 Sonic 就不能出现?
希望您能理解我的问题,并提前致谢。 :)
【问题讨论】:
-
C++ 标准现在不鼓励在 C++ 代码中使用 rand/srand。它与您的问题并不完全相关,但请考虑使用
标头 -
或者在 Qt 应用程序中使用 qrand()。
标签: c++ arrays string qt random