473,729 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Convert an integer to a string? Plan B?

http://public.research.att.com/~bs/b...#int-to-string

Is there no C library function that will take an int and convert it to its
ascii representation? The example Bjarne shows in his faq is not extremely
convenient.
--
NOUN:1. Money or property bequeathed to another by will. 2. Something handed
down from an ancestor or a predecessor or from the past: a legacy of
religious freedom. ETYMOLOGY: MidE legacie, office of a deputy, from OF,
from ML legatia, from L legare, to depute, bequeath. www.bartleby.com/61/
Mar 7 '06 #1
43 8447
Steven T. Hatton wrote:
http://public.research.att.com/~bs/b...#int-to-string

Is there no C library function that will take an int and convert it to its
ascii representation? The example Bjarne shows in his faq is not extremely
convenient.


sprintf

V
--
Please remove capital As from my address when replying by mail
Mar 7 '06 #2
Steven T. Hatton wrote:
http://public.research.att.com/~bs/b...#int-to-string

Is there no C library function that will take an int and convert it to its
ascii representation? The example Bjarne shows in his faq is not extremely
convenient.


The example Stroustrup gives is the best way. Compare:

http://www.parashift.com/c++-faq-lit....html#faq-39.2
http://www.parashift.com/c++-faq-lit....html#faq-39.3

As the FAQ notes, you could use C facilities rather than C++, but the
latter should be preferred.

See also Boost's lexical_cast.

Cheers! --M

Mar 7 '06 #3
mlimber wrote:

As the FAQ notes, you could use C facilities rather than C++, but the
latter should be preferred.


However, it doesn't say why the "C++" approach should be preferred.
(Yes, I'm aware that it's possible to pass too small an output buffer to
the C functions. Don't do that.)

C provides perfectly good conversion functions. The "C++" approach,
creating a stringstream object which you then throw away, is extremely
expensive. I would never use it.

--

Pete Becker
Roundhouse Consulting, Ltd.
Mar 7 '06 #4
mlimber wrote:
The example Stroustrup gives is the best way. Compare:

http://www.parashift.com/c++-faq-lit....html#faq-39.2
http://www.parashift.com/c++-faq-lit....html#faq-39.3

As the FAQ notes, you could use C facilities rather than C++, but the
latter should be preferred.

See also Boost's lexical_cast.

Cheers! --M


The whole idea is to have one little call such as itos there when you need
it. I usually want to do it in a situation such as :

virtual const char* what() const throw() {
std::string message(_myName );
message+="\n\t" ;
message+=""!=_n amespaceName? _namespaceName+ "::":"";
message+=""!=_c lassName ? _className +"::":"";

message+=""!=_f ile?" File: "+_file :"";
message+= 0!=_line?" Line: "+itos(_line):" ";

message+=_messa ge;

return message.toStdSt ring().c_str();
}
Note that I have not yet tested this with std::string. I am converting code
that used Qt QString, which provides a QString::setNum (int).
--
NOUN:1. Money or property bequeathed to another by will. 2. Something handed
down from an ancestor or a predecessor or from the past: a legacy of
religious freedom. ETYMOLOGY: MidE legacie, office of a deputy, from OF,
from ML legatia, from L legare, to depute, bequeath. www.bartleby.com/61/
Mar 7 '06 #5
Pete Becker wrote:
C provides perfectly good conversion functions.
.... which are harder to use than might seem. Both the buffer size
and the conversion specifiers are potential stumbling blocks. Of
course, any experienced C programmers knows these.
The "C++" approach,
creating a stringstream object which you then throw away, is extremely
expensive. I would never use it.


It is actually a shame that there is no simple and efficient method
addressing this issue. Of course, what actually qualifies as simple
and/or efficient depends on the user's view. I would use something
like the code below:

#include <algorithm>
#include <limits>

template <typename V, typename OutIt>
OutIt convert(V v, OutIt to)
{
enum { bsize = std::numeric_li mits<V>::digits 10 + 2 };
bool neg = v < 0;

char buffer[bsize], *tmp = buffer + bsize;
*--tmp = "0123456789 "[(neg? -(v + (v < -10? 10: 0)): v) % 10];
v /= 10;

if (neg)
v = -v;

for (; v > 0; v /= 10)
*--tmp = "0123456789 "[v % 10];

if (neg)
*--tmp = '-';
return std::copy(tmp, buffer + bsize, to);
}

Of course, when used with an inappropriate iterator it also gives
the potential of a buffer overrun. ... but it also allows for
perfectly save use e.g. when using 'std::back_inse rter()' together
with an 'std::string' as the destination.
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.eai-systems.com> - Efficient Artificial Intelligence
Mar 7 '06 #6
In article <5N************ *************** ***@speakeasy.n et>,
"Steven T. Hatton" <ch********@ger mania.sup> wrote:
http://public.research.att.com/~bs/b...#int-to-string

Is there no C library function that will take an int and convert it to its
ascii representation? The example Bjarne shows in his faq is not extremely
convenient.


How could it be any more convenient?

template < typename T, typename U >
T lexical_cast( const U& u ) {
std::stringstre am ss;
T t;
if ( !( ss << u && ss >> t ) ) throw std::bad_cast() ;
return t;
}

The above can be used exactly like any of the other casting operators
that C++ provides. Boost provides a much more optimized version if you
find it necessary.

--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Mar 7 '06 #7
In article <ps************ ********@gigane ws.com>,
Pete Becker <pe********@acm .org> wrote:
mlimber wrote:

As the FAQ notes, you could use C facilities rather than C++, but the
latter should be preferred.

However, it doesn't say why the "C++" approach should be preferred.
(Yes, I'm aware that it's possible to pass too small an output buffer to
the C functions. Don't do that.)


Passing a too small buffer, and type safety are the two reasons I can
think of off hand, there may be more.

When it comes down to it, the C++ approach has less undefined behavior.
In order to "just don't do that" one must know all the things that one
shouldn't do. Obviously, the fewer things there are, the easer it will
be to not do them.

C provides perfectly good conversion functions.
"perfectly" ? I think "adequate" would be a more appropriate adjective,
as in "barely sufficient or satisfactory". But that's just me, YMMV.

The "C++" approach,
creating a stringstream object which you then throw away, is extremely
expensive. I would never use it.


I use stringstreams for this purpose all over my code and I've never had
a user complain that it's too slow because of it. Yes, I've written code
that's "too slow", that's part of the nature of writing games, but
profiling showed other parts of the code that were far more expensive
than stringstreams.
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Mar 7 '06 #8

"Steven T. Hatton" <ch********@ger mania.sup> skrev i meddelandet
news:b6******** *************** *******@speakea sy.net...
mlimber wrote:
The example Stroustrup gives is the best way. Compare:

http://www.parashift.com/c++-faq-lit....html#faq-39.2
http://www.parashift.com/c++-faq-lit....html#faq-39.3

As the FAQ notes, you could use C facilities rather than C++, but
the
latter should be preferred.

See also Boost's lexical_cast.

Cheers! --M


The whole idea is to have one little call such as itos there when
you need
it. I usually want to do it in a situation such as :

virtual const char* what() const throw() {
std::string message(_myName );
message+="\n\t" ;
message+=""!=_n amespaceName? _namespaceName+ "::":"";
message+=""!=_c lassName ? _className +"::":"";

message+=""!=_f ile?" File: "+_file :"";
message+= 0!=_line?" Line: "+itos(_line):" ";

message+=_messa ge;

return message.toStdSt ring().c_str();
}
Note that I have not yet tested this with std::string.


No, obviously! :-)

This is exactly why using C style char pointers are so dangerous. As
soon as the function returns, the message goes out of scope, and is
destroyed.

Guess what happens to the pointer?
(You also cannot say that what() doesn't throw, when any of the string
operations might throw a bad_alloc.)
Bo Persson


Mar 7 '06 #9
Daniel T. wrote:
In article <ps************ ********@gigane ws.com>,
Pete Becker <pe********@acm .org> wrote:

mlimber wrote:
As the FAQ notes, you could use C facilities rather than C++, but the
latter should be preferred.

However, it doesn't say why the "C++" approach should be preferred.
(Yes, I'm aware that it's possible to pass too small an output buffer to
the C functions. Don't do that.)

Passing a too small buffer,


Yup. You have to know something about conversions to get conversions right.
and type safety are the two reasons I can
think of off hand,
We're talking about converting an int. Write it once, get it right, end
of discussion.
there may be more.
There may not be. Doesn't affect this discussion.

When it comes down to it, the C++ approach has less undefined behavior.
Nope. Write it once, get it right. No undefined behavior.

Oh, you meant "less opportunity to screw up if you're careless". Well,
that's true. Programming isn't a job for careless people.
In order to "just don't do that" one must know all the things that one
shouldn't do. Obviously, the fewer things there are, the easer it will
be to not do them.
Easier isn't the only goal, especially when any competent programmer
ought to be able to convert an int to a string with very little effort.
The "C++" approach,
creating a stringstream object which you then throw away, is extremely
expensive. I would never use it.

I use stringstreams for this purpose all over my code and I've never had
a user complain that it's too slow because of it. Yes, I've written code
that's "too slow", that's part of the nature of writing games, but
profiling showed other parts of the code that were far more expensive
than stringstreams.


Gratuitously slow code isn't good design. The reasons for using a
stringstream simply aren't compelling, and the cost is high. If you
don't put the slow stuff in, you won't have to take it out later.

--

Pete Becker
Roundhouse Consulting, Ltd.
Mar 7 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
6189
by: IamZadok | last post by:
Hi I was wondering if anyone knew how to convert a string or an integer into a Static Char. Thx
3
10289
by: Convert TextBox.Text to Int32 Problem | last post by:
Need a little help here. I saw some related posts, so here goes... I have some textboxes which are designed for the user to enter a integer value. In "old school C" we just used the atoi function and there you have it. So I enquired and found the Convert class with it's promising ToInt32 method, great... but it doesn't work. The thing keeps throwing Format Exceptions all over the place. What is the "C#" way to do this??? code int wmin,...
4
7277
by: Andreas Klemt | last post by:
Hello, what has the better performance and what are you using? Dim myObj As Object = 70 a) Dim myInt As Integer = DirectCast(myObj, Integer) b) Dim myInt As Integer = Convert.ToInt32(myObj) Thanks, Andreas
6
43658
by: MrKrich | last post by:
I want to convert Hexadecimal or normal integer to Binary. Does VB.Net has function to do that? I only found Hex function that convert normal integer to Hexadecimal.
5
37331
by: Mika M | last post by:
Hi! I've made little code to convert string into hex string... Public ReadOnly Property ToHexString(ByVal text As String) As String Get Dim arrBytes As Integer() = CharsToBytes(text) Dim sb As StringBuilder = New StringBuilder For i As Integer = 0 To arrBytes.Length - 1
14
1463
by: Drew | last post by:
Hi All: I know I am missing something easy but I can't find the problem! I have a program which reads an integer as input. The output of the program should be the sum of all the digits in the integer that was entered. So, if 353 was entered, the output should be 11.
20
3441
by: Niyazi | last post by:
Hi all, I have a integer number from 1 to 37000. And I want to create a report in excel that shows in 4 alphanumeric length. Example: I can write the cutomerID from 1 to 9999 as: 1 ----> 0001 2 ----> 0002
7
6261
by: shellon | last post by:
Hi all: I want to convert the float number to sortable integer, like the function float2rawInt() in java, but I don't know the internal expression of float, appreciate your help!
1
2052
by: dean.brunne | last post by:
Hi, In the code below I scroll throught the firldnames of a query ignoring the first three then converting the remaining fields to first: the fieldnames as a record in a field called Product (e.g- Fieldname is BEER, convert to BEER as the record value in a field called product) Second: The values of the field to be populated in a field called Baseline Units. I capture the fieldname as a string but when the code below tries to populate...
0
9280
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9142
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8144
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2162
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.