Hey, I'm trying to print a string using textprint_ex, but whenever I get to the line of code that does that, the program crashes. The string itself shows fine in a console window when doing cout.
The line of code I use, is this:
textprintf_ex(buffer, font, 100, y, makecol(255, 255, 255), -1, "%s", test);
Anybody knows why it crashes, and how to fix it?
Let's see some more code.
1 | void load_highscores() { |
2 | int y = 50; |
3 | string line; |
4 | string test = "TEST"; |
5 | ifstream file ("High.txt"); |
6 | if (file.is_open()) { |
7 | while (!file.eof()){ |
8 | getline (file,line); |
9 | cout << test << "\n"; |
10 | textprintf_ex(buffer, font, 100, y, makecol(255, 255, 255), -1, "%s", test); |
11 | y += 20; |
12 | } |
13 | file.close(); |
14 | } |
15 | } |
When I comment out the textprintf_ex command, it all works smoothly, but with that command, it crashes.
That's because textprintf_ex wants a C-string, not a std::string. I'm surprised that even compiles.
It compiles because variadic functions don't typecheck "..." arguments.
Good to know.
instead of test use test.c_str()
That works like a charm, the .c_str():D Thanks for the help!
.c_str() returns a char array (C-style string) just like the string you used it on. Just felt the need to point that out.
It compiles because variadic functions don't typecheck "..." arguments.
It does if you add the printf attribute to the function. So either MSVC doesn't have a way to check it and he's using MSVC, or he has warnings off.
Warnings're turned on. Compiler's standard one in Dev-C++ (with the Allegro parameter).
Figuring out how to print strings got me so frustrated. I still have no idea where anyone could find out they had to add .c_str() to their string variable. I'm just glad someone on the forums knew.
I still have no idea where anyone could find out they had to add .c_str() to their string variable.
Google is your friend. Or your favorite porn search engine .
GullRaDriel: wow, you've answered almost every one of my posts today!
I still have no idea where anyone could find out they had to add .c_str() to their string variable.
From wherever you were supposed to have learned C++.
I learned C++ from gamedev.net, and a little right here.
Get a good free C++ book. I learnt about .c_str() from the one that should be on the first link, "thinking in C++" by Bruce Eckel.
Possumdude0: It's because I got nothing else to do today.
I second HoHo and Gnolam thought.