【问题标题】:How to use a random string for the window title bar?如何为窗口标题栏使用随机字符串?
【发布时间】:2025-12-13 12:50:01
【问题描述】:

我希望我的程序的标题栏是来自数组的随机字符串。我正在使用 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' 变量放在参数中。

【问题讨论】:

  • 可能希望将您的数组访问权限更改为rand() % 5,因为您的索引为 0-4。不过,不知道这是否能解决您的问题。
  • 这显示了数组中的第二个,谢谢。 :) 知道如何每次都显示不同的内容吗?
  • @Charles:你给随机数生成器 std::srand(std::time(nullptr)); 播种了吗?
  • 没有。我不完全确定将种子的一点点代码放在哪里。除了“glutCreateWindow()”之外,我发布的所有代码都不在方法中。这只是全球性的。而且我只能将 srand 放入一个方法中。
  • @Charles:直接在 WinMain 或 main(无论你使用哪个)开始添加即可。

标签: c++ opengl


【解决方案1】:

不确定是什么问题,除了 %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() 或始终使用相同的种子,则每次运行都会得到相同的输出。

【讨论】:

    最近更新 更多