converting a number (1234) into a string ("1234")

Started by
6 comments, last by donjonson 19 years, 1 month ago
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!
Advertisement
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.
The best way is to use sprintf(itoa is non-standard)

sprintf(string, "%d", number);
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:

#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]
Rob Loach [Website] [Projects] [Contact]
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:
#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-
Professional C++ and .NET developer trying to break into indie game development.
Follow my progress: http://blog.nuclex-games.com/ or Twitter - Topics: Ogre3D, Blender, game architecture tips & code snippets.
This is a great topic. I never knew there were so many ways to do this.
These tears..leave scars...as they run down my face.

This topic is closed to new replies.

Advertisement