c++ - 使用 al_ustr_newf 复制字符串 Allegro 5

标签 c++ string stdstring allegro5

我试图在我的游戏中制作排行榜,但我遇到了一个我无法弄清楚的问题。 我的文本文件中有带名称的字符串和带分数的整数。我尝试将它们复制到 ALLEGRO_USTR 以在屏幕上显示。

当我使用 al_ustr_newf("%s", name1) 时,它会复制一些随机符号。

fstream file2;
file2.open("leaderboard.txt", ios_base::in);

string name1;
string name2;
string name3;
int temp_score1;
int temp_score2;
int temp_score3;

file2 >> name1 >> temp_score1;
file2 >> name2 >> temp_score2;
file2 >> name3 >> temp_score3;

ALLEGRO_USTR * ustr_name1 = NULL;
ustr_name1 = al_ustr_newf("%s", name1);

也许还有另一种方法可以在 allegro 5 中复制字符串?

最佳答案

来自 al_ustr_newf reference :

Create a new string using a printf-style format string.

Notes:

The "%s" specifier takes C string arguments, not ALLEGRO_USTRs. Therefore to pass an ALLEGRO_USTR as a parameter you must use al_cstr, and it must be NUL terminated. If the string contains an embedded NUL byte everything from that byte onwards will be ignored.

也就是说,al_ustr_newf("%s", name1); 是未定义的行为,遍历堆栈变量直到找到 NUL 字节。 std::string 的地址几乎从不与实际缓冲区的地址相同。

使用 al_ustr_newf("%s", name1.c_str());,就像您必须处理 printfstd::字符串.

关于c++ - 使用 al_ustr_newf 复制字符串 Allegro 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37486134/

相关文章:

c++ - 将Qt GUI拆分成多线程用于GUI、模拟、OpenGL是否可行?

c++ - Makefile:无需执行任何操作

c++ - 新接触窗口应用程序的人应该学习 X、GTK+ 还是什么?

c++ - 尝试编译一个qt项目,在各个地方出现输入/输出错误

string - bash:在多个其他字符串中查找字符串

c - C中的字符串初始化

c# - 如何安全地将字节数组转换为字符串并返回?

C++ std::string 如何用多个双引号格式化字符串文字?

c++ - 使用类似于 strndup 的语义从 char[] 创建 std::string

c++ - 如何访问 std::string 内的 char 数组?