473,320 Members | 1,746 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Re: Integer to string conversion

pradeep wrote:
Hello friends:

I know some people here don't like to answer C++ questions, but I
believe this is really about the underlying C code. Anyway I have
posted as well to the other group someone suggested
("comp.lang.c++") just in case.

I think the problem is that in my C++ class, we were taught to use
cin, cout etc. but now I need to use the primitive C operations
printf etc. and I don't understand exactly how they work.

I'm trying to convert an integer into a string. Here's what I'm
trying, but when I try to output the string returned from the
function, I just get garbage. How should I be using sprintf?

Thanks.

char *App::IntToString(int i) //doesn't really rely on classes
{
char buf[2];
Not big enough by far and disappears once IntToString finishes.
char *out = buf;
No reason to have to do this.
sprintf(out, "%d", i);
sprintf( buf, "%d", i );
would also work, although there are hte other problems.
return out;
you are returning a pointer to a buffer that goes out of scope when the
function returns.
}
So, how to fix this? Simplest is to make the buffer static so it doesn't
disappear when the function returns and make it big enough. char buf[2];
is only large enough to hold "0" through "9". An integer can hold quite a
larger value, however. 10 or 11 digits I think.

char *App::IntToString(int i) //doesn't really rely on classes
{
static char buf[12];
sprintf(buf, "%d", i);
return buf;
}

Shoudl fix the immediate errors, but does not fix any design issues. Such
as the fact if you called this twice in a row, both returned char*'s would
point to the same value. I.E.

char* Value1;
char* Value2;

Value1 = IntToString( 10 );
Value2 = IntToString( 11 );

std::cout << Value1 << " " << Value2;

would output 11 11 since the pointers returned by IntToString are identical,
and the static buffer was changed.

It is better to return a std::string. You can do the conversion either as is
and convert to a std::string, or use use std::stringstream. (Untested
code).

std::string App::IntToString( int i )
{
std::stringstream Convert;
Convert << i;
std::string Answer;
Convert >Answer;

return Convert.string();
}

Personally, I use a template for this.

template<typename T, typename F T StrmConvert( const F from )
{
std::stringstream temp;
temp << from;
T to = T();
temp >to;
return to;
}

template<typename Fstd::string StrmConvert( const F from )
{
return StrmConvert<std::string>( from );
}

So I can do:

std::string Value = StrmConvert( 10 );

or even:

int Value = StrmConvert<int>( "10" );

Note that my StrmConvert does not have any error checking, any errors would
simply return a default constructed value. I.E. If you tried to convert
"xyz" to an int the result would be 0.
--
Jim Langston
ta*******@rocketmail.com

Jun 27 '08 #1
0 1225

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

Similar topics

7
by: Sashi | last post by:
Two questions: (1) I can pull the text of an XML element as a string just fine using code as such: strSomeString = myXmlDoc.SelectSingleNode("/Element1/Element2/Element3",...
8
by: Brent Lievers | last post by:
Greetings, I have a question about parsing a fixed-width integer from a string. Lines of data are being read from a file having a very strict column-delimited format. In my example below,...
15
by: Teresa | last post by:
1) Should I use Integer.Parse to convert a string into an integer in .NET now? CType(sUserID, Integer) OR Integer.Parse(sUserID) 2) And is it better to use the string class to trim, get length,...
5
by: Barry | last post by:
Hello, In VS2003, I tried using an enum and setting it into a field in a datarow. It seems as if the datatype of the field in the row determined what went into the field. If the datatype was...
11
by: nephish | last post by:
Hello there, i need a way to check to see if a certain value can be an integer. I have looked at is int(), but what is comming out is a string that may be an integer. i mean, it will be formatted...
1
by: charles_gero | last post by:
Hi all, I had a question about the topics in the subject and posted to comp.std.c, but feel it may also be appropriate here. Please excuse this crosspost if it is in bad form. I have a...
10
by: Dave griffiths | last post by:
Hi all Using VB2005 on Vista with a Norwegian locale setup. The test program has 3 textboxes the sum held in txt3. Using the code below, txt2 conversion causes an error when it is left empty....
7
by: Spoon | last post by:
Hello everyone, In my code, I use uint16_t (exactly 16-bit-wide unsigned integer type) and I need to print their value in base 10. ...
5
by: pradeep | last post by:
Hello friends: I know some people here don't like to answer C++ questions, but I believe this is really about the underlying C code. Anyway I have posted as well to the other group someone...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.