Conversion Part 2: A better way?

E

Evyn

Hi all,

Sorry for asking a second question today.

I have the task of reading a text file with a string of length x on
each line. My task is to convert x to a double between 0 and 1. For
example:

File Output
123 0.123
6786 0.6786

I have the following code, which seems to work, but it strikes me
there may be a better way that avoids so many concatanations.

double convert(string s)
{
double x;
string str = "." + s;
x = atof(str.c_str());
return x;
}


Thanks for your time again.

Jim
 
J

James Kanze

I have the task of reading a text file with a string of length
x on each line. My task is to convert x to a double between 0
and 1.

You want to convert the length of the string to a double between
0 and 1?
For example:
File Output
123 0.123
6786 0.6786

That's pure textual manipulation:

std::string word ;
while ( in >> word ) {
out << "0." << word ;
}

Adjust for whatever error checking is necessary on the input.

About the only special case would be if you have to handle an
optional sign, e.g.:

std::string word ;
while ( in >> word ) {
if ( word[ 0 ] == '-' || word[ 0 ] == '+' ) {
out << word[ 0 ] << "0." << word.substr( 1 ) ;
} else {
out << "0." << word ;
}
}
I have the following code, which seems to work, but it strikes me
there may be a better way that avoids so many concatanations.
double convert(string s)
{
double x;
string str = "." + s;
x = atof(str.c_str());
return x;
}

The conversions are more likely to be a problem than the
concatentations, although if you're reading and writing from a
file, I doubt that either will have any real effect. Note too
that if the input is something like "100", the output will still
only by ".1"; this may or may not be what you want.
 

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,772
Messages
2,569,593
Members
45,112
Latest member
BrentonMcc
Top