Thread: Convert string to double and the back?

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    11

    Convert string to double and the back?

    Hey,
    I'm writing a function to read a set of strings and doubles from an input file, and I now want to send them back to the main program. The function returns each value from the input file at a time, but I cant see how I can deal with returning two different types of data from one function.

    I've got two ideas as to how I could do this, but no clue on how to implement them:

    1) Convert all of the values (strings and numeric values) to doubles, return them to main and then convert the strings stored as a double back to a string type.

    2) Return all of the values as their respective data type. Can a single function be used to more than one data type?

    Unfortunately I am not sure how to do either of these, does anyone have any ideas?

    Thanks alot,
    Kieran

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    And how is your calling function supposed to know what it's getting?

    (You could define a struct with a string and a double in it, plus a code to say which one it has, and return that.)

    But all that leads up to: how is your function that reads in supposed to know what it's going to get? Is there a format to the input file?

  3. #3
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    You can return by pointer parameters.

    Code:
    void func(int *return1, double *return2) {
         *return1 = 1;
         *return2 = 1.0;
    }
    
    int main() {
         int a;
         double b;
         func(&a, &b);
    }

  4. #4
    Registered User
    Join Date
    Apr 2009
    Posts
    11
    Thanks for the suggestions, I'll try the struct approach.

    Yea, each value has a prefix to tell the function what to do with it.

Popular pages Recent additions subscribe to a feed