How do I put numbers into a string?

Started by
5 comments, last by Jingo 19 years, 4 months ago
I want to display the FPS in my program and I'm passing a char* to my text blitter function, but I can't find any help documentation on putting the int values in a string/char.
Advertisement
In C, you can use sprintf or (better) snprintf.
A preferable C++ alternative would be using a stringstream (just like any ostream), obtaining the resulting string, and using the c_str( ) member to get a char* member.

Although in that case, you will need to be passing a const char * to your blitter function (or create a copy from it by hand before passing it).
Heh. Guess I missed that. Thanks, I've tried both methods and they work.
or use the itoa() function.
Quote:Original post by Jimmy Valavanis
or use the itoa() function.


Unless, of course, you are programming for a platform which doesn't have that non-standard function.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Example of string streams:

#include <sstream>#include <iostream>using namespace std;int SomeInt = 8534895;char *Str = "Some String";//join the two togetherstringstream StrStream;StrStream << Str << " " << SomeInt;//output the string as a const char*cout << StrStream.str().c_str();


The above snippet will display "Some String 8534895"
char *Str = "Some String"; involves a deprecated conversion in c++.

This topic is closed to new replies.

Advertisement