【发布时间】:2022-01-14 17:16:17
【问题描述】:
我正在使用 C++ 为游戏创建菜单,但在读取文本文件 (.cfg) 时出现问题,我想将其显示到屏幕上(使用 SDL,而不是控制台)。
问题是在 SDL 中,我只得到最后一行。这是为什么呢?
这是我的代码:
fstream characters;
characters.open("characters.cfg", ios::in);
while (getline(characters, line))
cout << line << endl;
我创建了一个字符串来用 SDL_ttf 显示它:
void renderUI() {
SDL_Surface* textSurface;
SDL_Texture* textTexture;
SDL_Rect textRect;
SDL_Color white = { 255,255,255 };
textRect.w = 250;
textRect.h = 20;
textRect.x = 150;
textRect.y = 200;
string names = line;
textSurface = TTF_RenderText_Blended(gameFont, names.c_str(), white);
textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
if (textSurface == NULL)
{
cout << "TTF_RenderText_Solid() Failed: " << TTF_GetError() << endl;
TTF_Quit();
SDL_Quit();
exit(1);
}
SDL_RenderCopy(renderer, textTexture, NULL, &textRect);
}
这里有一张照片显示我在控制台中获得了全文,但在 SDL 中没有:
示例照片:
【问题讨论】:
-
不应该移动矩形以防止覆盖之前写入的内容吗?
-
看起来
line本身在getline循环中不断被覆盖。当renderUI有机会画出任何东西时,Highlander's Law 已经开始了,Shang Tsung 是最后一根绳子。 -
您可能希望将这些行存储在
std::vector或类似名称中。但要小心。lines具有全局变量的恶臭,可以在 getline 循环加载它或renderUI读取它时更改。不要对vector犯同样的错误。