473,320 Members | 1,865 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.

converting to const char*

I wrote a function to convert any type to string:

template <typename T>
std::string toStr(const T &thing) {
std::ostringstream outStr;
outStr << thing;
return outStr.str();
}

the above function works properly. I also wrote another function to
convert any type to const char* but it doesent work properly

template <typename T>
const char* toCStr(const T &thing) {
std::ostringstream outStr;
outStr << thing;
std::string Str=outStr.str();
return Str.c_str();
}

Does any body know what is its problem?

Thanks

Apr 9 '07 #1
11 2421
* sadegh:
>
template <typename T>
const char* toCStr(const T &thing) {
std::ostringstream outStr;
outStr << thing;
std::string Str=outStr.str();
return Str.c_str();
}

Does any body know what is its problem?
You're returning a pointer to a an object that no longer exists after
returning; this is known as a "dangling" pointer (or reference).

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Apr 9 '07 #2
So what shoud I do to convert any type to const char*?

Apr 9 '07 #3
sadegh wrote:
So what shoud I do to convert any type to const char*?
Does the caller expect to have to delete the memory on the returned string ?
Apr 9 '07 #4
On Apr 9, 10:39 am, Gianni Mariani <gi3nos...@mariani.wswrote:
sadegh wrote:
So what shoud I do to convert any type to const char*?

Does the caller expect to have to delete the memory on the returned string ?
I dont know. but for example I want to call the toCStr() function like
these:

AfxMessageBox(toCStr(8)); // showing the number "8"

or

m_EditBox.SetWindowText(toCStr(8)); // insert the number "8" into an
edit box

Tanks.

Apr 9 '07 #5
On Apr 9, 10:16 am, "sadegh" <sadegh...@yahoo.comwrote:
template <typename T>
const char* toCStr(const T &thing) {
std::ostringstream outStr;
outStr << thing;
std::string Str=outStr.str();
return Str.c_str();

}
Does any body know what is its problem?
you need to ensure the converted string lives outside the scope of
this function. one simple way is to do that is:
--
template <typename T>
const char* toCStr(const T &thing) {
static std::ostringstream outStr;
outStr.str("");
outStr << thing;
return outStr.str().c_str();
}
--
note that there's only one covnersion buffer, all users of toCStr
would need to make deep copies of the result and not rely on its
contents.

thanks,

Apr 9 '07 #6
sadegh wrote:
On Apr 9, 10:39 am, Gianni Mariani <gi3nos...@mariani.wswrote:
>>sadegh wrote:
>>>So what shoud I do to convert any type to const char*?

Does the caller expect to have to delete the memory on the returned string ?


I dont know. but for example I want to call the toCStr() function like
these:

AfxMessageBox(toCStr(8)); // showing the number "8"

or

m_EditBox.SetWindowText(toCStr(8)); // insert the number "8" into an
edit box
What you want is an object that extends the life of the string until the
function call returns. The catch with this is that the lifetime of the
string is very short, although longer than a dead return value. Once
the expression is evaluated, the memory of the string is no longer
valid. Hence, don't be caught holding on to a pointer from the toCStr
below otherwise you will run into nasty probs.

// toCStr header

#include <sstream>
#include <string>

template <typename T>
std::string ToString( const T & val )
{
std::ostringstream l_out;
l_out << val;
return l_out.str();
}

struct toCStr
{
const std::string m_value;

template <typename T>
toCStr( const T & ival )
: m_value( ToString( ival ) )
{
}

operator const char * () const
{
return m_value.c_str();
}
};

/// example code

#include <iostream>

void foo( const char * str )
{
std::cout << str << "\n";
}

int main()
{
foo( toCStr( 8 ) );
}
Apr 9 '07 #7
On Apr 9, 1:37 pm, Gianni Mariani <gi3nos...@mariani.wswrote:
sadegh wrote:
On Apr 9, 10:39 am, Gianni Mariani <gi3nos...@mariani.wswrote:
>sadegh wrote:
>>So what shoud I do to convert any type to const char*?
>Does the caller expect to have to delete the memory on the returned string ?
I dont know. but for example I want to call the toCStr() function like
these:
AfxMessageBox(toCStr(8)); // showing the number "8"
or
m_EditBox.SetWindowText(toCStr(8)); // insert the number "8" into an
edit box

What you want is an object that extends the life of the string until the
function call returns. The catch with this is that the lifetime of the
string is very short, although longer than a dead return value. Once
the expression is evaluated, the memory of the string is no longer
valid. Hence, don't be caught holding on to a pointer from the toCStr
below otherwise you will run into nasty probs.

// toCStr header

#include <sstream>
#include <string>

template <typename T>
std::string ToString( const T & val )
{
std::ostringstream l_out;
l_out << val;
return l_out.str();

}

struct toCStr
{
const std::string m_value;

template <typename T>
toCStr( const T & ival )
: m_value( ToString( ival ) )
{
}

operator const char * () const
{
return m_value.c_str();
}

};

/// example code

#include <iostream>

void foo( const char * str )
{
std::cout << str << "\n";

}

int main()
{
foo( toCStr( 8 ) );

}- Hide quoted text -

- Show quoted text -- Hide quoted text -

- Show quoted text -
What a nice answer and a nicer example. THANK YOU VERY MUCH Gianni.

Apr 9 '07 #8
On Apr 9, 7:16 am, "sadegh" <sadegh...@yahoo.comwrote:
I wrote a function to convert any type to string:

template <typename T>
std::string toStr(const T &thing) {
std::ostringstream outStr;
outStr << thing;
return outStr.str();

}
You're reinventing the wheel there. Have a look at
boost::lexical_cast. It is very similar to your code. http://www.boost.org/

- Johan Levin

Apr 9 '07 #9
aiooua wrote:
template <typename T>
const char* toCStr(const T &thing) {
static std::ostringstream outStr;
outStr.str("");
outStr << thing;
return outStr.str().c_str();
}
--
note that there's only one covnersion buffer, all users of toCStr
would need to make deep copies of the result and not rely on its
contents.

thanks,
Here's one place where a macro has a tiny bit of use.

template <typename Tstd::string toStr(const T& thing) {
std::ostringstream outStr;
outStr << thing;
reutrn outStr.str();
}

#define toCStr(t) (toStr(t).c_str())

The temporary string returned by toStr() (and the c_str() from it)
will last until the end of thefull expression.
Apr 9 '07 #10
On Apr 9, 5:05 pm, Ron Natalie <r...@spamcop.netwrote:
aiooua wrote:
template <typename T>
const char* toCStr(const T &thing) {
static std::ostringstream outStr;
outStr.str("");
outStr << thing;
return outStr.str().c_str();
}
--
note that there's only one covnersion buffer, all users of toCStr
would need to make deep copies of the result and not rely on its
contents.
thanks,

Here's one place where a macro has a tiny bit of use.

template <typename Tstd::string toStr(const T& thing) {
std::ostringstream outStr;
outStr << thing;
reutrn outStr.str();

}

#define toCStr(t) (toStr(t).c_str())

The temporary string returned by toStr() (and the c_str() from it)
will last until the end of thefull expression.
An Excellent Answer!!!!!!!!!!!! you are very smart Ron.

Apr 9 '07 #11
On Apr 9, 7:38 am, "sadegh" <sadegh...@yahoo.comwrote:
So what shoud I do to convert any type to const char*?
You shouldn't. Any more than you should try to generically
convert any type to string---it just doesn't make sense.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 10 '07 #12

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

Similar topics

4
by: jagmeena | last post by:
Hello, I am sure this problem has been addressed before, however, I could'nt get a suitable solution to my problem. Hence I am posting here. Thanks a lot for all your help. The code I have is ...
20
by: Nate | last post by:
I am working on an Oakley parser and want to call an fopen function to read in the log file. I can use this to read the file, but only if I pass a "const char" variable to fopen. Since I would...
7
by: jamihuq | last post by:
Hello, I would like to convert the following inline function to a macro. Can someone help? Thx Jami inline char * fromDESC(const char * &aDesC)
3
by: fakeprogress | last post by:
How would I go about converting this C code to C++? /* LIBRARY is an array of structures */ /* This function compares 'tcode' with */ /* existing codes in the array. */ /* It...
9
by: Gregory.A.Book | last post by:
I am interested in converting sets of 4 bytes to floats in C++. I have a library that reads image data and returns the data as an array of unsigned chars. The image data is stored as 4-byte floats....
2
by: pookiebearbottom | last post by:
Just looking for opinion on which of the 3 methods below people use in their code when they convert a 'const char *' to a 'const std::string &' came across #3 in someone's code and I had to...
11
by: hamishd | last post by:
Is this possible? Sorry if this question isn't relevant here. actually, I'm really trying to convert a unsigned char * to an int
5
by: Hans Mull | last post by:
Hi! How can I convert a string to a const unsigned char*? (string::c_str() converts the string to a signed char) Thanks in advance, Hans
35
by: Sean Farrow | last post by:
Hi: What is best and safest way of converting a char* to a const char *? Can I use const_cast? Cheers Sean.
7
by: ma740988 | last post by:
Consider the equation (flight dynamics stuff): Yaw (Degrees) = Azimuth Angle(Radians) * 180 (Degrees) / 3.1415926535897932384626433832795 (Radians) There's a valid reason to use single...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
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: 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)...
0
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...
0
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....

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.