用strtok拆分C-String

时间:2017-04-26 18:13:31

标签: c++ strtok c-strings

我正在寻找一种以特定方式从带有strtok的C-String中提取值的方法。我有一个C-String,我需要取出一个数字,然后将其转换为double。我能够轻松地转换为double,但是我需要它只根据请求的“度”来拉一个值。基本上,0度将从字符串中拉出第一个值。由于我正在使用的循环,我目前的代码遍历整个C字符串。有没有办法只针对一个特定的值并让它拉出那个双值?

    #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;
    }

1 个答案:

答案 0 :(得分:0)

为简单起见,您要问如何将标记化程序中的第N个元素确定为double。这是一个建议:

#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?
}