By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,847 Members | 2,285 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,847 IT Pros & Developers. It's quick & easy.

Double to string conversion

P: n/a
Hi there,

Is there a way to convert a double value to a string. I know that there
is fcvt() but I think this function is not a part of the standard
library. I want sth from the standard if possible.

The thing I am trying to do is to convert a double value to a string
with 8 elements. 8 is fixed because of the files I work with. I will
change this 8 character string with the one(8 character string) already
in the file and so on. But I have to do the conversion first.

Any help will be appreciated,

Thanks in advance.

Feb 27 '06 #1
Share this Question
Share on Google+
21 Replies


P: n/a
#include <sstream>
#include <iomanip>
#include <iostream>

using namespace std;
stringstream Text;
double Somevalue = 9.987654;

Text << Somevalue;

cout << Text.str() << endl;

// TODO: Lookup the iomanip stuff to get the format you want
--
Regards, Ron AF Greve

http://moonlit.xs4all.nl

"utab" <um********@gmail.com> wrote in message
news:11**********************@i39g2000cwa.googlegr oups.com...
Hi there,

Is there a way to convert a double value to a string. I know that there
is fcvt() but I think this function is not a part of the standard
library. I want sth from the standard if possible.

The thing I am trying to do is to convert a double value to a string
with 8 elements. 8 is fixed because of the files I work with. I will
change this 8 character string with the one(8 character string) already
in the file and so on. But I have to do the conversion first.

Any help will be appreciated,

Thanks in advance.

Feb 27 '06 #2

P: n/a
TB
utab skrev:
Hi there,

Is there a way to convert a double value to a string. I know that there
is fcvt() but I think this function is not a part of the standard
library. I want sth from the standard if possible.

The thing I am trying to do is to convert a double value to a string
with 8 elements. 8 is fixed because of the files I work with. I will
change this 8 character string with the one(8 character string) already
in the file and so on. But I have to do the conversion first.

Any help will be appreciated,

Thanks in advance.


#include <sstream>
#include <string>

template<typename T>
std::string AnyToString(T t) {
std::ostringstream sstrm;
sstrm << t;
return sstrm.str();
}

--
TB @ SWEDEN
Feb 27 '06 #3

P: n/a
Thx for the quick reply Moonlit.

Feb 27 '06 #4

P: n/a
Thx TB

Feb 27 '06 #5

P: n/a
I want to raise a long integer to another long integer and have the
result as a long integer. Is there a nice way to do this, or do I have
to use this approach:
(long)pow((double)some_long_integer,(int)some_othe r_long_integer)
?
It seems very unnecessary and risky (in terms of potential data loss).

An unrelated problem is that when passing multidimensional arrays as
parameters to functions, it’s necessary to specify the depths of all but
the first dimension. The compiler says that these must be constant (not
variables), but I need to specify the depths using variables which are
declared constant and whose values are known at compile time. Is this
possible?

Martin
Feb 27 '06 #6

P: n/a
Martin posted:
I want to raise a long integer to another long integer and have the
result as a long integer.


Why not just write a function. Potentially buggy code:
/***************************
Undefined Behaviour if
either argument is zero
***************************/

unsigned long RaisePowerInteger(unsigned long a, unsigned long b)
{
unsigned long value = a;

for ( unsigned long i = 0; i < b; ++i )
{
value *= a;
}

return value;
}
Feb 27 '06 #7

P: n/a

Martin wrote:
An unrelated problem is that when passing multidimensional arrays as
parameters to functions, it's necessary to specify the depths of all but
the first dimension. The compiler says that these must be constant (not
variables), but I need to specify the depths using variables which are
declared constant and whose values are known at compile time. Is this
possible?


Yes, you need to use compile time constants but they need not be
constant literals. Can you post a minimal code example that is causing
you a problem.

Have you got a good reason to rule out a vector of vectors [of vectors
....] in preference to raw arrays?

Gavin Deane

Feb 27 '06 #8

P: n/a
On 2006-02-27, Tomás <NU**@NULL.NULL> wrote:
Martin posted:
I want to raise a long integer to another long integer and have the
result as a long integer.


Why not just write a function. Potentially buggy code:
/***************************
Undefined Behaviour if
either argument is zero
***************************/

unsigned long RaisePowerInteger(unsigned long a, unsigned long b)
{
unsigned long value = a;

for ( unsigned long i = 0; i < b; ++i )
{
value *= a;
}

return value;
}


Is this a new term of "undefined" that is specific to this language?

Certainly "defined" but incorrect because isnt any number raised to the power
of 0 equal to 1?

The function is defined in that if b is 0, the answer will be a. If a
is zero then the answer is 0.

--
Remove evomer to reply
Feb 27 '06 #9

P: n/a
Tomás wrote:
Martin posted:

I want to raise a long integer to another long integer and have the
result as a long integer.

Why not just write a function. Potentially buggy code:
/***************************
Undefined Behaviour if
either argument is zero
***************************/

unsigned long RaisePowerInteger(unsigned long a, unsigned long b)
{
unsigned long value = a;

for ( unsigned long i = 0; i < b; ++i )
{
value *= a;
}

return value;
}


Good idea, thanks!

Martin
Feb 27 '06 #10

P: n/a
Gavin Deane wrote:
Martin wrote:
An unrelated problem is that when passing multidimensional arrays as
parameters to functions, it's necessary to specify the depths of all but
the first dimension. The compiler says that these must be constant (not
variables), but I need to specify the depths using variables which are
declared constant and whose values are known at compile time. Is this
possible?

Yes, you need to use compile time constants but they need not be
constant literals. Can you post a minimal code example that is causing
you a problem.

Have you got a good reason to rule out a vector of vectors [of vectors
...] in preference to raw arrays?

Gavin Deane


Thanks for your reply.

Code snippet:
------------------------------------------
double MC(double K,
double S[],
double v[],
double d[],
double r,
double exDates[],
const unsigned long DIMENSIONS,
const unsigned long GRIDPOINTS,
double frontiers[][DIMENSIONS][GRIDPOINTS], // Here's the problem
double gridStep[],
unsigned long evaldate,
unsigned long NumberOfPaths)
------------------------------------------

The reason for not using vectors of vectors of vectors instead of
threedimensional arrays is that the code is intended for parallel
computing, currently using MPI, and a colleague encountered difficulties
sending vectors between nodes. Perhaps there's a way around that though.

Is it much easier to use nested vectors (I suppose you mean the Vector
class?) as function parameters, than multidimensional arrays?

This is my first program in C/C++.

Martin
Feb 27 '06 #11

P: n/a

Martin wrote:
Gavin Deane wrote:
Martin wrote:
An unrelated problem is that when passing multidimensional arrays as
parameters to functions, it's necessary to specify the depths of all but
the first dimension. The compiler says that these must be constant (not
variables), but I need to specify the depths using variables which are
declared constant and whose values are known at compile time. Is this
possible?

Yes, you need to use compile time constants but they need not be
constant literals. Can you post a minimal code example that is causing
you a problem.

Have you got a good reason to rule out a vector of vectors [of vectors
...] in preference to raw arrays?

Gavin Deane


Thanks for your reply.

Code snippet:
------------------------------------------
double MC(double K,
double S[],
double v[],
double d[],
double r,
double exDates[],
const unsigned long DIMENSIONS,
const unsigned long GRIDPOINTS,
double frontiers[][DIMENSIONS][GRIDPOINTS], // Here's the problem
double gridStep[],
unsigned long evaldate,
unsigned long NumberOfPaths)
------------------------------------------


Ah, no you can't do that. DIMENSIONS and GRIDPOINTS are not
compile-time constants. Nothing tells the compiler what value they
have. You can do something like

const int size = 42;

void foo(int array2d[][size])
{
// ...
}

because the value of 'size' is known to the compiler when it encounters
foo. But that doesn't seem to be what you want.

As a style issue, avoid using ALL_CAPS for anything except macros
(which themselves should be avoided wherever possible) - and always use
ALL_CAPS when you must have a macro. That will protect you from having
your code stomped all over by the preprocessor.
The reason for not using vectors of vectors of vectors instead of
threedimensional arrays is that the code is intended for parallel
computing, currently using MPI, and a colleague encountered difficulties
sending vectors between nodes. Perhaps there's a way around that though.

Is it much easier to use nested vectors (I suppose you mean the Vector
class?) as function parameters, than multidimensional arrays?
Yes.

#include <vector>

typedef std::vector<std::vector<std::vector<int> > > vec3d;

void foo(const vec3d& v)
{
// ...
}

int main()
{
vec3d bar; // Use appropriate constructor to make the vectors the
right size.
foo(bar);
}

Also, any memory management and the associated exception safety is
taken care of for you.
This is my first program in C/C++.


There's no such language as C/C++. I hope that doesn't sound pedantic.
You may be well aware of what I am about to say, and by "C/C++" you may
mean "C or C++", in which case you can ignore the following. But there
is a common misconception that C and C++ are similar and that C++ is
just C expanded a bit, which leads people to say "C/C++" without
understanding the differences. C and C++ are very different. Some
things that are legal C are not legal C++. More importantly though,
within the common subset of the two languages, techniques regarded as
good practice in C are often porr C++.

It sounds like you may have a good reason to avoid std::vector in this
case, but it's generally good practice to use the standard library
tools in preference to hand written equivalents when you can. They are
designed to make your life easier and they achieve that.

Gavin Deane

Feb 27 '06 #12

P: n/a
Gavin Deane wrote:
Martin wrote:
Gavin Deane wrote:
Martin wrote:
An unrelated problem is that when passing multidimensional arrays as
parameters to functions, it's necessary to specify the depths of all but
the first dimension. The compiler says that these must be constant (not
variables), but I need to specify the depths using variables which are
declared constant and whose values are known at compile time. Is this
possible?
Yes, you need to use compile time constants but they need not be
constant literals. Can you post a minimal code example that is causing
you a problem.

Have you got a good reason to rule out a vector of vectors [of vectors
...] in preference to raw arrays?

Gavin Deane

Thanks for your reply.

Code snippet:
------------------------------------------
double MC(double K,
double S[],
double v[],
double d[],
double r,
double exDates[],
const unsigned long DIMENSIONS,
const unsigned long GRIDPOINTS,
double frontiers[][DIMENSIONS][GRIDPOINTS], // Here's the problem
double gridStep[],
unsigned long evaldate,
unsigned long NumberOfPaths)
------------------------------------------

Ah, no you can't do that. DIMENSIONS and GRIDPOINTS are not
compile-time constants. Nothing tells the compiler what value they
have. You can do something like

const int size = 42;

void foo(int array2d[][size])
{
// ...
}

because the value of 'size' is known to the compiler when it encounters
foo. But that doesn't seem to be what you want.

As a style issue, avoid using ALL_CAPS for anything except macros
(which themselves should be avoided wherever possible) - and always use
ALL_CAPS when you must have a macro. That will protect you from having
your code stomped all over by the preprocessor.

The reason for not using vectors of vectors of vectors instead of
threedimensional arrays is that the code is intended for parallel
computing, currently using MPI, and a colleague encountered difficulties
sending vectors between nodes. Perhaps there's a way around that though.

Is it much easier to use nested vectors (I suppose you mean the Vector
class?) as function parameters, than multidimensional arrays?

Yes.

#include <vector>

typedef std::vector<std::vector<std::vector<int> > > vec3d;

void foo(const vec3d& v)
{
// ...
}

int main()
{
vec3d bar; // Use appropriate constructor to make the vectors the
right size.
foo(bar);
}

Also, any memory management and the associated exception safety is
taken care of for you.

This is my first program in C/C++.

There's no such language as C/C++. I hope that doesn't sound pedantic.
You may be well aware of what I am about to say, and by "C/C++" you may
mean "C or C++", in which case you can ignore the following. But there
is a common misconception that C and C++ are similar and that C++ is
just C expanded a bit, which leads people to say "C/C++" without
understanding the differences. C and C++ are very different. Some
things that are legal C are not legal C++. More importantly though,
within the common subset of the two languages, techniques regarded as
good practice in C are often porr C++.

It sounds like you may have a good reason to avoid std::vector in this
case, but it's generally good practice to use the standard library
tools in preference to hand written equivalents when you can. They are
designed to make your life easier and they achieve that.

Gavin Deane


Thanks Gavin! I learned a lot from your answers. I used compile-time
constants which worked well.

As for the nested vector approach, I'm a little curious to know how one
uses an appropriate constructor to make the vectors the right size. Is
it complicated?

From now on I'm programming in C++, as opposed to C or the nonexistent
C/C++ :-)
It sounds like you may have a good reason to avoid std::vector in this
case, but it's generally good practice to use the standard library
tools in preference to hand written equivalents when you can. They are
designed to make your life easier and they achieve that.


Do you mean that nested vectors are more standard than multidimensional
arrays?

Martin
Feb 27 '06 #13

P: n/a
Richard G. Riley wrote:
<snip>
Certainly "defined" but incorrect because isnt any number raised to the power
of 0 equal to 1?


Not if this number is zero.

- J.
Feb 27 '06 #14

P: n/a
"Martin" <li*******@cti.ecp.fr> wrote in message
news:dt**********@smilodon.ecp.fr...
: Tomás wrote:
: > Martin posted:
: >
: >
: >>I want to raise a long integer to another long integer and have the
: >>result as a long integer.
: >
: >
: > Why not just write a function. Potentially buggy code:
: >
: >
: > /***************************
: > Undefined Behaviour if
: > either argument is zero
: > ***************************/
: >
: > unsigned long RaisePowerInteger(unsigned long a, unsigned long b)
: > {
: > unsigned long value = a;
: >
: > for ( unsigned long i = 0; i < b; ++i )
: > {
: > value *= a;
: > }
: >
: > return value;
: > }
:
: Good idea, thanks!

Well, only if you can afford making a lot of multiplications
( the above has linear complexity w.r.t. b ).
Logarithmic complexity can be achieved with little more
effort:

unsigned long RaisePowerInteger(unsigned long a, unsigned long b)
{
unsigned long result = 1;
for( ; b > 0 ; b>>=1 )
{
if(b&1) result *= a;
a *= a;
}
return result;
}

Further optimization is possible, but that's an easy start.
I hope this helps,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Feb 27 '06 #15

P: n/a
Ivan Vecerina wrote:
"Martin" <li*******@cti.ecp.fr> wrote in message
news:dt**********@smilodon.ecp.fr...
: Tomás wrote:
: > Martin posted:
: >
: >
: >>I want to raise a long integer to another long integer and have the
: >>result as a long integer.
: >
: >
: > Why not just write a function. Potentially buggy code:
: >
: >
: > /***************************
: > Undefined Behaviour if
: > either argument is zero
: > ***************************/
: >
: > unsigned long RaisePowerInteger(unsigned long a, unsigned long b)
: > {
: > unsigned long value = a;
: >
: > for ( unsigned long i = 0; i < b; ++i )
: > {
: > value *= a;
: > }
: >
: > return value;
: > }
:
: Good idea, thanks!

Well, only if you can afford making a lot of multiplications
( the above has linear complexity w.r.t. b ).
Logarithmic complexity can be achieved with little more
effort:

unsigned long RaisePowerInteger(unsigned long a, unsigned long b)
{
unsigned long result = 1;
for( ; b > 0 ; b>>=1 )
{
if(b&1) result *= a;
a *= a;
}
return result;
}

Further optimization is possible, but that's an easy start.
I hope this helps,
Ivan


Great, thanks!

Martin
Feb 27 '06 #16

P: n/a
Martin wrote:
I want to raise a long integer to another long integer and have the
result as a long integer. Is there a nice way to do this, or do I have
to use this approach:
(long)pow((double)some_long_integer,(int)some_othe r_long_integer)
?
It seems very unnecessary and risky (in terms of potential data loss).


FWIW I wrote various pow functions which can be either evaluated at
compile time or easily optimised to a constant.

//Easily optimisable pow function

template <unsigned int Exp>
inline long pow( int base)
{
return base * pow<Exp-1>(base);
}

template<>
inline long pow<0>(int base) { return 1;}

int main()
{
std::cout << pow<6>(10) <<'\n';
std::cout << pow<0>(10) <<'\n';
std::cout << pow<7>(2) << '\n';
std::cout << pow<32>(0x100) << '\n';
std::cout << pow<2>(0x100) <<'\n';
}

//compile time pow

template<typename Ta, Ta A,long B>
struct power;

template<typename Ta , Ta A>
struct power<Ta,A,0>{
static const Ta value = 1;
};

template<typename Ta, Ta A,long B>
struct power{
static const int value = power<Ta,A,B-1>::value*A;
};

int main()
{

std::cout << power<int,2,2>::value <<'\n';
}

It would be possible to make a constant time pow function with both
values runtime modifiable using the techniques at:
http://tinyurl.com/n6tsa

regards
Andy Little

Feb 27 '06 #17

P: n/a

Martin wrote in message ...
Gavin Deane wrote:
Martin wrote:
------------------------------------------
Is it much easier to use nested vectors (I suppose you mean the Vector
class?) as function parameters, than multidimensional arrays?


Yes.

#include <vector>

typedef std::vector<std::vector<std::vector<int> > > vec3d;

void foo(const vec3d& v){
// ...
}

int main(){
vec3d bar; // Use appropriate constructor to make the vectors the
right size.
foo(bar);
}

Also, any memory management and the associated exception safety is
taken care of for you.
Gavin Deane


Thanks Gavin! I learned a lot from your answers. I used compile-time
constants which worked well.

As for the nested vector approach, I'm a little curious to know how one
uses an appropriate constructor to make the vectors the right size. Is
it complicated?
Martin

This is what I came up with to init a 5x5x5 all set to 7.
Q(for others): Is there any simpler way to init this vector 'structure'? [ I
know a 2D 5x5 can be 'sized' with vector<vector<T> > vec2D(5, 5); ]. This
example looks 'butt ugly', but appears to work.
typedef std::vector<std::vector<std::vector<int> > > vec3d;

int main(){
// [ assume 'using std::vector;' in order to shorten line.]

vec3d vec3D( 5, vector<vector<int> >( 5, vector<int>( 5, int(7) ) ) );

cout<<"\n vec3D.at(0).at(0).size()= "<<vec3D.at(0).at(0).size();
cout<<"\n vec3D.at(0).at(0).at(0)= "<<vec3D.at(0).at(0).at(0)
<<std::endl;
// ......
} // main()end

// -- output --
// vec3D.at(0).at(0).size()= 5
// vec3D.at(0).at(0).at(0)= 7

--
Bob R
POVrookie
Feb 28 '06 #18

P: n/a

Martin wrote:
Code snippet:
------------------------------------------
double MC(double K,
double S[],
double v[],
double d[],
double r,
double exDates[],
const unsigned long DIMENSIONS,
const unsigned long GRIDPOINTS,
double frontiers[][DIMENSIONS][GRIDPOINTS], // Here's the problem
double gridStep[],
unsigned long evaldate,
unsigned long NumberOfPaths)
------------------------------------------

The reason for not using vectors of vectors of vectors instead of
threedimensional arrays is that the code is intended for parallel
computing, currently using MPI, and a colleague encountered difficulties
sending vectors between nodes. Perhaps there's a way around that though.

Is it much easier to use nested vectors (I suppose you mean the Vector
class?) as function parameters, than multidimensional arrays?

This is my first program in C/C++.

Martin


I believe std::valarray is what you want.

Feb 28 '06 #19

P: n/a

Martin wrote:
Gavin Deane wrote:
Martin wrote:
Is it much easier to use nested vectors (I suppose you mean the Vector
class?) as function parameters, than multidimensional arrays?


Yes.

#include <vector>

typedef std::vector<std::vector<std::vector<int> > > vec3d;

void foo(const vec3d& v)
{
// ...
}

int main()
{
vec3d bar; // Use appropriate constructor to make the vectors the
right size.
foo(bar);
}

Also, any memory management and the associated exception safety is
taken care of for you.


As for the nested vector approach, I'm a little curious to know how one
uses an appropriate constructor to make the vectors the right size. Is
it complicated?


I guess complicated is in the eye of the beholder. The construction
syntax is quite cumbersome if you've not seen it before. But what's
going on isn't too complicated, and the parameter passing syntax is a
lot simpler - no need to put the array sizes in the function
declaration at all (so avoiding the risk of making a mistake by, for
example, getting them the wrong way round or using the wrong values
entirely).

#include <vector>

typedef std::vector<std::vector<std::vector<int> > > vec3d;
const int dimensions = 5;
const int grid_points = 42;
const int the_third_one = 7;

int main()
{
vec3d bar(dimensions, std::vector<std::vector<int> >(grid_points,
std::vector<int>(the_third_one)));
}
> It sounds like you may have a good reason to avoid std::vector in this
> case, but it's generally good practice to use the standard library
> tools in preference to hand written equivalents when you can. They are
> designed to make your life easier and they achieve that.


Do you mean that nested vectors are more standard than multidimensional
arrays?


Not at all. Multideimensional arrays are part of the language and
std::vector is part of the library. Both are standard. The point is
that, if the standard library provides some tool that does what you
need, you are better of using it than writing your own equivalent code.
The standard library implementation will be well tested, familiar
(hopefully) to other C++ programmers working on you code, and should
lead you more quickly to a clear and correct program.

As a reference, this book is worth it's weight in gold IMO.
http://www.josuttis.com/libbook/

Gavin Deane

Feb 28 '06 #20

P: n/a

Gavin Deane wrote in message
<11**********************@t39g2000cwt.googlegroups .com>...

#include <vector>
typedef std::vector<std::vector<std::vector<int> > > vec3d;
const int dimensions = 5;
const int grid_points = 42;
const int the_third_one = 7;
Small (somewhat) safety issue; Those should be unsigned, not int.

const int dimensions = -5; // ouch, a HUGE size vector.
// vector ctor interprets it as unsigned.

const size_t dimensions = -5; // let the compiler warn first.
// I guess 'std::vector::size_type' would be even better (?).

to OP: the 'const' isn't required here, just good practice.
size_t dimensions( 5 );
std::vector<int> vecA(dimensions, int(42));
dimensions = 22;
std::vector<int> vecB(dimensions);

int main(){
vec3d bar(dimensions, std::vector<std::vector<int> >(grid_points,
std::vector<int>(the_third_one)));
// I guess that answers my question in my other post. Thanks!
}

Gavin Deane


Just a thought.
--
Bob R
POVrookie
Feb 28 '06 #21

P: n/a

BobR wrote:
Gavin Deane wrote in message
<11**********************@t39g2000cwt.googlegroups .com>...

#include <vector>
typedef std::vector<std::vector<std::vector<int> > > vec3d;
const int dimensions = 5;
const int grid_points = 42;
const int the_third_one = 7;
Small (somewhat) safety issue; Those should be unsigned, not int.

const int dimensions = -5; // ouch, a HUGE size vector.
// vector ctor interprets it as unsigned.

const size_t dimensions = -5; // let the compiler warn first.
// I guess 'std::vector::size_type' would be even better (?).


The vector constructor expects std::vector::size_type so that would be
the best choice, assuming you don't think you might be changing the
container to a deque or something later.
to OP: the 'const' isn't required here, just good practice.
size_t dimensions( 5 );
std::vector<int> vecA(dimensions, int(42));
dimensions = 22;
std::vector<int> vecB(dimensions);


Yes, another advantage of vectors is that you don't need to know the
sizes at compile time. But the discussion with the OP so far had been
around the concept of compile time constants. I just didn't want to add
too much information and risk confusion.

Gavin Deane

Mar 1 '06 #22

This discussion thread is closed

Replies have been disabled for this discussion.