【问题标题】:Copying string with al_ustr_newf Allegro 5使用 al_usr_newf Allegro 5 复制字符串
【发布时间】:2016-05-27 14:33:00
【问题描述】:

我尝试在游戏中创建排行榜,但遇到了一个我无法解决的问题。 我的文本文件中有带有名称的字符串和带有分数的整数。我尝试将它们复制到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 中复制字符串?

【问题讨论】:

    标签: c++ string stdstring allegro5


    【解决方案1】:

    来自al_ustr_newf reference

    使用 printf 样式的格式字符串创建一个新字符串。

    注意事项:

    “%s”说明符采用 C 字符串参数,而不是 ALLEGRO_USTRs。因此,要将 ALLEGRO_USTR 作为参数传递,您必须使用 al_cstr,并且它必须以 NUL 终止。如果字符串包含嵌入的 NUL 字节,则从该字节开始的所有内容都将被忽略。

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

    使用al_ustr_newf("%s", name1.c_str());,就像使用printfstd::string 一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      • 2015-12-31
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      相关资源
      最近更新 更多