How to convert a number to a string in this language?
label- & gt; Text = trackBar- & gt; Value;
Answer 1, authority 100%
Unfortunately, there is no normal standard way of converting numbers to strings in C++ 2003. Possible solutions:
-
sprintf
– C-style solution -
itoa
is another C-style option. Not a standard feature, but many implementations do. -
stringstream
:stringstream ss; int i = 777; ss & lt; & lt; i; string str = ss.str ();
-
For more complex conversions, you can use
boost :: format
C++ 11 finally has normal conversion functions, including std :: to_string
, overloaded for different numeric types. Works fine in g ++ – 4.7.
Answer 2, authority 25%
atoi (); from stdlib.h
Answer 3, authority 25%
@Fangog , he was surprised to find that in addition to sprintf () there is nothing standard. If needed, here is a function for different number systems. Binary to hexadecimal common digits. For the rest (up to 64-bit), the character set is from base64 (RFC1113).
You might be surprised, but printf
in Windows (at least 32-bit XP) does not work correctly with multiple arguments if there is a long long (64-bit integer) among them.
Faced with this fact, I wrote a transform function (well, and generalized it a bit).
If you find it useful, take it.
/ *
llstr.c avp 2011, 2012
Convert long-long fixed integer (64-bit) to string in the specified radix
(any 2..64 (bin, octal, decimal, hex ...))
Returns string length.
* /
#ifdef TEST
#include & lt; stdio.h & gt;
#include & lt; stdlib.h & gt;
#include & lt; string.h & gt;
#endif
int
my_llstr (long long v, // source for 'printing'
int radix,
int unsign, // if 1 then unsigned source
char * res) // memory for result
{
const char * dig = "0123456789abcdef";
static const char cb64 [] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 + /";
int rem [65], sp = 0; // stack for reminders
char * p = res; // for return length
unsigned long long u = v; // use if unsign == 1
if (! res)
return 0;
if (radix & lt; 2)
radix = 2;
if (radix & gt; 64)
radix = 64;
if (radix & gt; 16)
dig = cb64;
if (unsign) {
while (u & gt; = radix) {
rem [sp ++] = u% radix;
u = u / radix;
}
* res ++ = dig [u];
} else {
if (v & lt; 0) {
* res ++ = '-';
v = -v;
}
while (v & gt; = radix) {
rem [sp ++] = v% radix;
v = v / radix;
}
* res ++ = dig [v];
}
while (sp)
* res ++ = dig [rem [- sp]];
* res = 0;
return res-p;
}
#ifdef TEST
main (int ac, char * av [])
{
long x;
int n;
char buf [100];
int r = av [1]? atoi (av [1]): 10;
while (scanf ("% ld", & amp; x) == 1) {
n = my_llstr (x, r, 0, buf);
printf ("% s \ n", buf);
}
}
#endif
Answer 4
Since C++ 11, the language has a function to_string
:
int n = 1;
std :: string str = std :: to_string (n);