| Title: | C++ |
| Notice: | Read 1.* and use keywords (e.g. SHOW KEY/FULL KIT_CXX_VAX_VMS) |
| Moderator: | DECCXX::AMARTIN |
| Created: | Fri Nov 06 1987 |
| Last Modified: | Thu Jun 05 1997 |
| Last Successful Update: | Fri Jun 06 1997 |
| Number of topics: | 3604 |
| Total number of notes: | 18242 |
I can't believe I can't find the answer to this on my own...
How do I convert an int to a string? The following code fragment gets the
point across but seems likely to overflow...
main()
{
String s;
int blah = 404;
sprintf ( s, "%d", blah );
}
Thanks,
Bill
| T.R | Title | User | Personal Name | Date | Lines |
|---|---|---|---|---|---|
| 3552.1 | SPECXN::DERAMO | Dan D'Eramo | Wed Apr 23 1997 14:46 | 10 | |
You can avoid the overflow by sprintf-ing to a char array
first...
int blah = 404;
char buffer[SOME_SAFE_BUT_NOT_TOO_EXTRAVAGANT_BOUND];
int n = sprintf(buffer, "%d", blah); // this is truly...
assert(0 <= n && n < sizeof buffer); // ...paranoid :-)
String s(buffer);
Dan
| |||||
| 3552.2 | CIM2NI::THORPE | Wed Apr 23 1997 14:58 | 6 | ||
I was hoping there was a way without having to dummy up a char array - I guess I can stop wondering now. Thanks Dan. -Bill | |||||
| 3552.3 | SPECXN::DERAMO | Dan D'Eramo | Wed Apr 23 1997 15:14 | 8 | |
There are "string streams" which you can create, write to with
a sequence of "<<" operations, and then extract the entire
text written to them. That also has an intermediate
something, the stream. You can always define a function or
operator that takes a 'String &' and an 'int' and does the
work on an already constructed string.
Dan
| |||||