Double to string conversion

U

utab

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.
 
M

Moonlit

#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
 
T

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::eek:stringstream sstrm;
sstrm << t;
return sstrm.str();
}
 
M

Martin

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_other_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
 
T

Tomás

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

Gavin Deane

Martin said:
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
 
R

Richard G. Riley

Martin posted:


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.
 
M

Martin

Tomás said:
Martin posted:




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
 
M

Martin

Gavin said:
Martin said:
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
 
G

Gavin Deane

Martin said:
Gavin said:
Martin said:
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
 
M

Martin

Gavin said:
Martin said:
Gavin said:
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
 
J

Jacek Dziedzic

Richard G. Riley wrote:
Certainly "defined" but incorrect because isnt any number raised to the power
of 0 equal to 1?

Not if this number is zero.

- J.
 
I

Ivan Vecerina

: 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
 
M

Martin

Ivan said:
: 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
 
A

andy

Martin said:
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_other_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
 
B

BobR

Martin wrote in message ...
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
 
F

Fei Liu

Martin said:
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.
 
G

Gavin Deane

Martin said:
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,
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,818
Latest member
Brigette36

Latest Threads

Top