Geo wrote:
> Saurabh wrote:
> > Geo wrote:
> > > Saurabh wrote:
> > > > Ian Collins wrote:
> > > > > Saurabh wrote:
> > > > > > Hi all,
> > > > > >
> > > > > > I am working on RedHat Linux GCC 3.0.
> > > > > > I am trying to convert a long to string through sprintf.
> > > > > > but i m getting segmantation fault.
> > > > > > I tried snprintf also but no avail.here is the piece of code..
> > > > > >
> > > > > > ----------------------------
> > > > > > long myLong=200000;
> > > > > > char myStr[50];
> > > > > > memset[myStr,'\0',50];
> > > > > > sprintf(myStr,"%s",myLong);
> > > > > ^
> > > > > %s is for printing (C style) strings.
> > > > >
> > > > > use %ld, or use iostreams.
> > > > >
> > > > > --
> > > > > Ian Collins.
> > > >
> > > > hi Ian,
> > > > Thanks a lot.
> > > > You solved my problem.
> > > > actually I thought that the second argument to
> > > > sprintf() refers to the format you wish to convert
> > > > to,instead it refers to the format you wish to
> > > > convert from.
> > > > anyways..
> > > > thanks again.
> > > > saurabh
> > >
> > >
> > > I would suggest that if you are STILL using sprinf, then you haven't
> > > fixed the problem, it will surely break one day. Why not use
> > > boost::lexical_cast (or you're own similar code) instead.
> >
> > hi Geo,
> > I have never used boost::lexical_cast.Is this an STL component?
> > or are you hinting me to write my own version of sprintf()?
> >
> > Thanks & Regards
> > saurabh
>
> Hi,
>
> No I was suggesting you write you're own lexical cast function, if you
> can't use boost. You could start with something like this, you may want
> to make this more robust,
>
> template<typename out, typename in> out lexical_cast(const in &i)
> {
> std::stringstream ss;
> ss << i;
> out temp;
> ss >> temp;
> return temp;
> }
>
but g++ told me that:
In function `out lexical_cast(const in&) [with out = std::string, in =
int]':
instantiated from here
error: `ss' has incomplete type
error: storage size of `ss' isn't known
>
> then do
>
> int x = 123;
> std::string s = lexical_cast<std::string>(x);
>
> you can also do the reverse
>
> std::string s = "5678";
> int z = lexical_cast<int>(s);
|