1

I am looking for a way to pull a value from a C-String with strtok in a specific way. I have a C-String which I need to take out a number and then convert it to a double. I am able to convert to double easily enough, however I need it to only pull one value based on what "degree" is requested. Basically a degree of 0 will pull the first value out of the string. The code I currently has goes through the entire C-string due to the loop I am using. Is there a way to only target one specific value and have it pull that double value out?

    #include <iostream>
    #include <string>
    #include <cstring>
    using namespace std;

    int main() {

        char str[] = "4.5 3.6 9.12 5.99";
        char * pch;
        double coeffValue;

        for (pch = strtok(str, " "); pch != NULL; pch = strtok(NULL, " "))
        {
            coeffValue = stod(pch);
            cout << coeffValue << endl;
        }
        return 0;
    }
ajn678
  • 11
  • 1

1 Answers1

0

For the sake of simplicity, you're asking how to determine the Nth element in your tokenizer as a double. Here is a suggestion:

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main() {

    char str[] = "4.5 3.6 9.12 5.99";
    double coeffValue;

    coeffValue = getToken(str, 2);   // get 3rd value (0-based math)
    cout << coeffValue << endl;
    return 0;
}

double getToken(char *values, int n)
{
    char *pch;

    // count iterations/tokens with int i
    for (int i = 0, pch = strtok(values, " "); pch != NULL; i++, pch = strtok(NULL, " "))
    {
        if (i == n)     // is this the Nth value?
            return (stod(pch));
    }

    // error handling needs to be tightened up here.  What if an invalid
    // index is passed?  Or if the string of values contains garbage?  Is 0
    // a valid value?  Perhaps using nan("") or a negative number is better?
    return (0);         // <--- error?
}
CSmith
  • 13,318
  • 3
  • 39
  • 42