Search code examples
c++stringstdstringallegro5

Copying string with al_ustr_newf Allegro 5


I tried to make a leaderboard in my game but I've encountered a problem which I can't figure out. I have strings with names and integers with score from my text file. I try to copy them to ALLEGRO_USTR to show it on screen.

When I use al_ustr_newf("%s", name1), it copies some random signs.

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);

Maybe there's another way to copy strings in allegro 5?


Solution

  • From 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.

    That being said, al_ustr_newf("%s", name1); is undefined behaviour, iterating through your stack variables until it finds a NUL byte. Address of std::string is almost never the same as an address of the actual buffer.

    Use al_ustr_newf("%s", name1.c_str());, just like you'd have to do with printf and std::string.