Evyn wrote:
Sorry for asking a second question today.
.... and try not to post twice in five minutes...
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.
"So many"? Not sure what you mean. How many concatenations do you
think you have here? I counted one operator+.
If your buffer is long enough (and using 'std::string' has the
advantage of not pre-allocating the buffer), you could pre-stuff it
with the '.' and read into it starting from the second character,
thus appending at the time of reading, but that requires knowing
the buffer size ahead of time. 'std::string' has no such limitation.
double convert(string s)
If you don't change 's' itself (you could), then it's better to pass
it by ref to const:
double convert(string const& s)
{
double x;
string str = "." + s;
x = atof(str.c_str());
return x;
Rewrite it in a single line:
return atof((string(".") + s).c_str());
}
Thanks for your time again.
You can also rewrite it like so:
double convert(string s) // not ref to const
{
s.insert(s.begin(), '.');
return atof(s.c_str());
}
Whether it's going to be faster or not is unknown, can only be
determined by profiling.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask