473,769 Members | 4,601 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
43 8457
Roland Pibinger wrote:
On 11 Mar 2006 14:19:21 -0800, an**@servocomm. freeserve.co.uk wrote:
Pete Becker wrote:
But in general, low level functions should report errors in-channel,
because once you've added the overhead of throwing exceptions you can't
get rid of it. Applications that don't use exceptions shouldn't have to
pay for them.


I put them in because I do use them. If an empty string is returned
that is an error and must be acknowledged as such rather than ignored,
which is what happens IMO all to often if it can be ignored.


Actually, the conversion from int to string cannot fail because all
bit combinations in an int result in a valid value.

[snip]

Clause [3.9.1/1] makes that guarantee for unsigned character types. For the
type int, however, I think no such guarantee is made in the standard.
Best

Kai-Uwe Bux

Mar 12 '06 #31

Daniel T. wrote:
In article <44************ **@news.utanet. at>,
rp*****@yahoo.c om (Roland Pibinger) wrote:
On Sat, 11 Mar 2006 11:11:57 -0500, Pete Becker <pe********@acm .org>
wrote:
Daniel T. wrote:
> So, what is the "appropriat e test" to ensure that a buffer is not
> overrun?


Here's a proposal for a simple, efficient, and safe conversion
function:

#include <stdio.h>
#include <string>

inline std::string& itostr (int i, std::string& out) {
std::string::va lue_type buf[128];
int len = snprintf(buf, sizeof(buf), "%d", i);

if (len > 0 && size_t (len) < sizeof (buf)) {
out.assign(buf, std::string::si ze_type (len));
} else {
out.clear();
}
return out;
}


Why put a 128 char buffer on the stack when string already has one
imbedded in it...

string& itostr( int i, string& result )
{
result.clear();
if ( i == INT_MIN ) {
result += "-2147483648";
}
else if ( i == 0 ) {
result = '0';
}
else {
string::size_ty pe pos = 0;
if ( i < 0 ) {
result = '-';
i = -i;
pos = 1;
}
while ( i > 0 ) {
result.insert( pos, 1, char( '0' + i % 10 ) );
i /= 10;
}
}
return result;
}

string itostr( int i ) {
string result;
itostr( i, result );
return result;
}


Hmm ... Maybe somebody ought to test all these functions and see which
has the best features on grounds of speed, stack/heap used and also
reliability (IOW likelihood of failure or data corruption). Maybe even
the original stringstream wouldnt do too bad then ?

Then it should be not too difficult to write a standardisation proposal
.. I guess it has to be called itostr though!

regards
Andy Little

Mar 12 '06 #32

Daniel T. wrote:
[...]
result += "-2147483648";
}


BTW Thats not portable of course. You might be able to use BOOST
Preprocessor to stringize INT_MIN.:

http://www.boost.org/libs/preprocess...stringize.html

Anyway if that doesnt work I'm sure there would be some way to do it.

regards
Andy Little

Mar 12 '06 #33
On 11 Mar 2006 16:50:04 -0800, an**@servocomm. freeserve.co.uk wrote:
In that case things are much simpler. Now I added a traits class for
the format string so potentially extending the useage to other integer
types, though it seems sprintf is a bit limited to signed and unsigned
int only..whatever. ..

#include <cstdio>
#include <limits>
#include <string>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_integral.hpp >

....

Ahem, wasn't a simple solution desired?
Mar 12 '06 #34
Roland Pibinger wrote:
Andy Little wrote
#include <cstdio>
#include <limits>
#include <string>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_integral.hpp > ...

Ahem, wasn't a simple solution desired?


I like to use enable_if. It improves (IMO) the error message if I
passed a double rather than a int for example. So it makes my life a
bit simpler. However its not in the C++ standard I guess Try code
below re that ----->

BTW It would also be useful to template param the string char_type then
wrap sprintf/swprintf in a functor and select based on the char_type.
Then the function would be even simpler wouldnt it .... ;-)

regards
Andy Little

-----------------------
#include <cstdio>
#include <limits>
#include <string>

// comment/uncomment to check difference in error messages
#define USE_ENABLE_IF

#ifdef USE_ENABLE_IF
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_integral.hpp >
#endif

template <typename IntegerType>
struct format;

template <>
struct format<int>{
static const char* specifier(){ret urn "%d";}
};
template <>
struct format<unsigned int>{
static const char* specifier(){ret urn "%u";}
};

template <typename IntegerType>
inline
#ifdef USE_ENABLE_IF
typename boost::enable_i f<
boost::is_integ ral<IntegerType >,
std::string&::type

#else
std::string&
#endif
itostr (IntegerType i, std::string& out)
{
std::string::va lue_type buf[
std::numeric_li mits<IntegerTyp e>::digits10 + 3
];
std::string::si ze_type len
= std::sprintf(bu f, format<IntegerT ype>::specifier (), i);
out.assign(buf, len);
return out;
}

#include <iostream>
int main()
{
std::string str;
itostr(1.,str);
}

regards
Andy Little

Mar 12 '06 #35
On Sun, 12 Mar 2006 03:58:25 GMT, "Daniel T."
<po********@ear thlink.net> wrote:
Why put a 128 char buffer on the stack when string already has one
imbedded in it...
because it costs nothing. But I probably change it to
std::string::va lue_type buf[3 * sizeof(int) + 1];
string& itostr( int i, string& result )
{
result.clear();
this may delete the internal buffer for some string implementations
if ( i == INT_MIN ) {
result += "-2147483648";
}
else if ( i == 0 ) {
result = '0';
}
else {
string::size_ty pe pos = 0;
if ( i < 0 ) {
result = '-';
i = -i;
pos = 1;
}
while ( i > 0 ) {
result.insert( pos, 1, char( '0' + i % 10 ) );
this may cause string reallocations for some string implementations
(IIRC even some professional implementations )
i /= 10;
}
}
return result;
}


With the *printf functions you can format the string output. An
extended version of the above function could offer output format
alternatives to users. Not as format string but in a safe way.

Best wishes,
Roland Pibinger
Mar 12 '06 #36
an**@servocomm. freeserve.co.uk wrote:
Daniel T. wrote:
[...]

result += "-2147483648";
}

BTW Thats not portable of course. You might be able to use BOOST
Preprocessor to stringize INT_MIN.:


You're looking for a string that converts to the minimum representable
value?

#define XSTR(x) #x
#define STR(x) XSTR(x)
STR(INT_MIN)

But note that on some implementations , INT_MIN is defined more like
(-2147483657-1).

--

Pete Becker
Roundhouse Consulting, Ltd.
Mar 12 '06 #37

Pete Becker wrote:
an**@servocomm. freeserve.co.uk wrote:
Daniel T. wrote:
[...]

result += "-2147483648";
}

BTW Thats not portable of course. You might be able to use BOOST
Preprocessor to stringize INT_MIN.:


You're looking for a string that converts to the minimum representable
value?

#define XSTR(x) #x
#define STR(x) XSTR(x)
STR(INT_MIN)

But note that on some implementations , INT_MIN is defined more like
(-2147483657-1).


hmm..IIRC Its you that started us on this rocky road, further up this
thread. Now look where its ended up using nested macros!

OK How about this... just to initalise that value:

#include <sstream>
#include <iostream>
#include <string>

std::string
int_min_init()
{
std::ostringstr eam s;
s << INT_MIN;
return s.str();
}
std::string const & int_min()
{
static std::string const& str = int_min_init();
return str;
}

// now use
result += int_min();

See .. I can still get an ostringstream in somewhere... :-)

regards
Andy Little

Mar 12 '06 #38
In article <44************ **@news.utanet. at>,
rp*****@yahoo.c om (Roland Pibinger) wrote:
On Sun, 12 Mar 2006 03:58:25 GMT, "Daniel T."
<po********@ear thlink.net> wrote:
Why put a 128 char buffer on the stack when string already has one
imbedded in it...


because it costs nothing. But I probably change it to
std::string::va lue_type buf[3 * sizeof(int) + 1];
string& itostr( int i, string& result )
{
result.clear();


this may delete the internal buffer for some string implementations


Then change the line to:
result.reserve( numeric_limits< float>::digits1 0 + 2 );

or some such. But then you have a problem with "result = ..." calls
below because they *may* reduce the size of the internal buffer thus
defeating the reserve call.
if ( i == INT_MIN ) {
result += "-2147483648";
}
else if ( i == 0 ) {
result = '0';
}
else {
string::size_ty pe pos = 0;
if ( i < 0 ) {
result = '-';
i = -i;
pos = 1;
}
while ( i > 0 ) {
result.insert( pos, 1, char( '0' + i % 10 ) );


this may cause string reallocations for some string implementations
(IIRC even some professional implementations )
i /= 10;
}
}
return result;
}


With the *printf functions you can format the string output. An
extended version of the above function could offer output format
alternatives to users. Not as format string but in a safe way.


But then your right back to using something very much like stringstream
which Mr. Becker (and apparently only Mr Becker) finds "too expensive".
--
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 12 '06 #39
In article <11************ *********@i39g2 000cwa.googlegr oups.com>,
an**@servocomm. freeserve.co.uk wrote:
Hmm ... Maybe somebody ought to test all these functions and see which
has the best features on grounds of speed, stack/heap used and also
reliability (IOW likelihood of failure or data corruption). Maybe even
the original stringstream wouldnt do too bad then ?

Then it should be not too difficult to write a standardisation proposal
. I guess it has to be called itostr though!


I don't think itostr is a good name. Personally, I like
lexical_cast<Ty pe>. As in:

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;
}

template < >
std::string lexical_cast<st d::string>( const int& u ) {
// do whatever you think is "least expensive" here Pete.
}
--
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 12 '06 #40

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

Similar topics

5
6194
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
10293
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
7283
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
43663
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
37335
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
3447
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
6264
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
2054
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
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9997
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
9865
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
8873
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...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5310
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3965
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
3
2815
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.