I am pretty sure it is possible, but I am not sure how to turn a real variable into a string variable (using string.h).
Printable View
I am pretty sure it is possible, but I am not sure how to turn a real variable into a string variable (using string.h).
I was given some of these links looking for the same thing:
http://rafb.net/efnet_cpp/faq/conversions/int2string/
http://www.parashift.com/c++-faq-lit....html#faq-39.1
http://www.boost.org/libs/conversion/lexical_cast.htm
And I was given some code that works similrly to atoi by another member:
I wrote this assuming by <string.h> you meant <string> and std::string's. If you merely wanted char* strings, than you can use atoi() in <cstdio>Code:void append_int(std::string & s, unsigned int n)
{
unsigned int tmp = 0;
while (n) {
tmp *= 10;
tmp += n % 10;
n /= 10;
}
while (tmp) {
s.push_back('0' + tmp % 10);
tmp /= 10;
}
}
Alright and yes I ment string not string.h. That first link you gave me worked perfectly!
Thanks for passing along the help!
You could use stringstreams. Do a board search if you want more. They've been discussed several times recently. Just, use them as a normal stream when dealing with floating point numbers.
And, atoi( ) goes the wrong way. ;)
Damnit! itoa() ;)
There is only a minor problem with that one:
Best sticking with:Quote:
Portability.
Not defined in ANSI-C. Supported by some compilers.
1. stringstream
2. sprintf
3. your own "home-brew" function
With heavy preference for the first.
Cheers
This is in the faq...
Code:#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int x = 10;
string s;
stringstream ss;
ss << x;
s = ss.str();
cout << s << endl;
cin.get();
return 0;
}
I usualy do it like this:
(string)(char*)variable
i dont think you have ever really used that...
and had it work, at least if this is what your meaning
by your post
Code:#include <iostream>
#include <string>
using namespace std;
int main()
{
int length = 10;
string mystring = (string)(char*)length;
cout << mystring << endl;
cin.get();
return 0;
}
cause it doesnt work.
Quote:
Originally Posted by ILoveVectors
That is exactly what I am using.
Just make sure you don't use this function for any value of n that is ten digits long and ends in 4, 5, 6, 7, 8, or 9. [Some values that end in 4 work -- namely those with tens digit 1 or 0. Most ten-digit numbers that end in "24" also work -- but if the hundreds digit is 9, they might not. (If the reversed form of the number is 4294967296 or higher, the function breaks.)] Assuming that an int is 32 bits long.Quote:
Originally Posted by Tonto
I'd go with using a char array as a stack instead of another int, next time around. So just use stringstreams :-)
Check out wsprintf()
wsprintf is for use with wchar_t, not char. sprintf would generally be the appropriate function.