gpt4 book ai didi

c++ - 如何为窗口标题栏使用随机字符串?

转载 作者:行者123 更新时间:2023-11-28 08:07:47 25 4
gpt4 key购买 nike

我希望程序的标题栏是数组中的随机字符串。我正在使用 FreeGLUT 来初始化窗口(“glutCreateWindow()”函数),但我不确定如何让它工作。

这是我所拥有的:

std::string TitleArray[] = 
{
"Window title 1",
"Window title 2",
"Window title 3",
"Window title 4",
"Window title 5"
};
std::string wts = TitleArray[rand() % 6];

const char* WINDOW_TITLE = wts.c_str();

这里是“glutCreateWindow()”调用:

glutCreateWindow(WINDOW_TITLE);

不过,每当我调试时,标题栏都是空白的。 “glutCreateWindow()”函数也需要一个 const char*,所以我不能只将“wts”变量放在参数中。

最佳答案

不确定是什么问题,除了 %6 而不是 %5。这是一个显示 rand() 使用的示例控制台程序:

#include "stdafx.h"
#include <string>
#include <iostream>
#include <time.h>

std::string TitleArray[] =
{
"Window title 1",
"Window title 2",
"Window title 3",
"Window title 4",
"Window title 5"
};

using std::cout;
using std::endl;

int _tmain(int argc, _TCHAR* argv[])
{
srand ( time(NULL) ); // seed with current time
for(int i=0; i<20; ++i)
{
std::string wts = TitleArray[rand() % 5];
cout << wts.c_str() << endl;
}
return 0;
}


Console output:

Window title 3
Window title 4
Window title 5
Window title 2
Window title 4
Window title 4
Window title 1
Window title 3
Window title 2
Window title 1
Window title 2
Window title 1
Window title 2
Window title 5
Window title 4
Window title 5
Window title 3
Window title 1
Window title 4
Window title 1
Press any key to continue . . .

如果您省略 srand() 或始终使用相同的种子,则每次运行都会获得相同的输出。

关于c++ - 如何为窗口标题栏使用随机字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9900840/

25 4 0