Problem returning double from function

I am new to C++ and have a problem. I am compiling code with GCC for an ARM processor and have a function that returns a doubel value. Prototype is:
double TextToFloat(char * stringIn);
Here is the problem: The function works fine if it is part of the file where it is called but if I move it to another file it calculates the return value correctly in the routine but the return statement returns garbage. I figure I must be doing something simple that is wrong but it beats me what it is. ANy help would be appreciated.
Post some code otherwise we have no idea what you are talking about.
OK, here is the routine:

double TextToFloat(char * stringIn)
{

double number;
unsigned char decimal=0,i=0,sign=0;
unsigned long decimalPlace=10;
number=0;
if (stringIn[0]=='-')
{
sign=1;
i++;
}
while(stringIn[i]!=0)
{
if (stringIn[i]=='.')
{
decimal=1;

}
else
{
if (decimal==1)
{
number=number+(double)(stringIn[i]-48)/decimalPlace;
decimalPlace=decimalPlace*10;
}
else number=number*10+(double)(stringIn[i]-48);
}
i++;
}
if (sign) number=number*-1;
return number;
}

It takes stringIn and turns it into a floating point number. It works fine when defined in the file where it is called but returns garbage when defined in another file.
I have no idea why it should behave differently if placed in a separate file. However there are simpler ways to convert a string to a double:

1
2
3
4
5
6
7
8
9
#include <string>
#include <sstream>

double TextToFloat(const std::string& str)
{
    double d;
    std::istringstream(str) >> d;
    return d;
}
Thanks, unfortunately sstream is not supported in this compiler. I did figure out that it works if I change from double to float so it must be something in how it treats the double designation.
Why is sstream missing? Is this an embedded application?
@ ragbagger

I can't find fault with it. Is it possible that the strings you are passing in are somehow doing something? How are you calling this?

EDIT: Passing in a null string will cause a problem though.
Last edited on
What about this? That is if you can't use the <sstream> header then use the c-run time library function.
http://cplusplus.com/reference/clibrary/cstdlib/strtod/
Topic archived. No new replies allowed.