E
Evyn
Hi all,
I have recently asked for advice:
http://groups.google.com/group/comp...1b/e63d8f10b51f015c?lnk=raot#e63d8f10b51f015c
My task is to convert a string of characters to a double. The string
is read from a file and will be in the format 12345. The double output
must be 0.12345.
My answer to this problem was:
double convert(string s)
{
return atof((string(".") + s).c_str());
}
The prof. was happy, but he told me to write my own atof. So I have
converted the string to an array of char. Is this the right strategy?
If so, how to I actually convert the array to a double? (As you no
doubt can see, I am pretty much in the dark here).
double stof(string s)
{
// c_str - Returns a pointer to a null-terminated array of
characters representing the string's contents.
const char* p = s.c_str();
int len = strlen(p); // get length
char sArr[len];
memcpy(sArr, s.c_str(), len); // copy to char array
double tmp;
for(int i = 0;i<len;i++)
{
cout << endl << i << " = " << sArr; // gives expected
output
tmp = (sArr - 48); // gives expected number
}
return tmp;
}
Regards,
Jim
I have recently asked for advice:
http://groups.google.com/group/comp...1b/e63d8f10b51f015c?lnk=raot#e63d8f10b51f015c
My task is to convert a string of characters to a double. The string
is read from a file and will be in the format 12345. The double output
must be 0.12345.
My answer to this problem was:
double convert(string s)
{
return atof((string(".") + s).c_str());
}
The prof. was happy, but he told me to write my own atof. So I have
converted the string to an array of char. Is this the right strategy?
If so, how to I actually convert the array to a double? (As you no
doubt can see, I am pretty much in the dark here).
double stof(string s)
{
// c_str - Returns a pointer to a null-terminated array of
characters representing the string's contents.
const char* p = s.c_str();
int len = strlen(p); // get length
char sArr[len];
memcpy(sArr, s.c_str(), len); // copy to char array
double tmp;
for(int i = 0;i<len;i++)
{
cout << endl << i << " = " << sArr; // gives expected
output
tmp = (sArr - 48); // gives expected number
}
return tmp;
}
Regards,
Jim