converting a number (1234) into a string ("1234")
my fn I adapted from aaroncox.net's tutorials to use SDL to write strings to the screen seems to dislike me passing it anything other than strings... so how would I go about converting a int into a string? (Or just getting it to print the int) Thanks!
Look into the function ITOA() it converts integers to strings.
I believe it's in the "stdlib.h" Header. It's not ANSI-C but it should work with most compilers.
I believe it's in the "stdlib.h" Header. It's not ANSI-C but it should work with most compilers.
Quote:Original post by DerAnged
The best way is to use sprintf(itoa is non-standard)
sprintf(string, "%d", number);
Didnt know that about itoa.
Quote:Original post by DerAnged
The best way is to use sprintf(itoa is non-standard)
sprintf(string, "%d", number);
Damnit I can't believe I forgot sprintf!
I use a stringstream:
[Edited by - Rob Loach on March 23, 2005 8:14:24 AM]
#include <iostream>#include <string>#include <sstream>template <class T>inline std::string ToString(T data){ std::ostringstream s; s << data; return s.str();}int main(){ double e = 2.7183; float pi = 3.14159; int someInt = 1234; std::string strPi= ToString(pi); std::string strInt = ToString(someInt); std::string strE = ToString(e); std::cout << "Pi: " << strPi << std::endl; std::cout << "someInt: " << strInt << std::endl; std::cout << "e: " << strE << std::endl; std::cin.get(); return 0;}
[Edited by - Rob Loach on March 23, 2005 8:14:24 AM]
Then, of course there are those people that tell you sprintf() is the worst way to do it, because of typesafety, buffer overflows and stuff ;)
The clean option for those strange C++ guys happens to look like this, idea loosely taken from Boost:
:D
-Markus-
The clean option for those strange C++ guys happens to look like this, idea loosely taken from Boost:
#include <string>#include <sstream>template<typename TargetType, typename SourceType>inline TargetType lexical_cast(SourceType from) { std::stringstream s; s << from; TargetType to; s >> to; return to;}int main() { using namespace std; // number to string string x = lexical_cast<string>(123.456); // and vice versa float y = lexical_cast<float>(x + "789");}
:D
-Markus-
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement