c++ - 使用 strtok 拆分 C 字符串

标签 c++ strtok c-strings

我正在寻找一种以特定方式使用 strtok 从 C 字符串中提取值的方法。我有一个 C 字符串,我需要取出一个数字,然后将其转换为 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;
    }

最佳答案

为了简单起见,您问的是如何将分词器中的第 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?
}

关于c++ - 使用 strtok 拆分 C 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43641642/

相关文章:

c++ - 将内联 ASM 转换为 x64 igraph 的内在

c++ - 在 Windows 上安装 node-gd

c++ - 如何使用 QPainter 缩放文本以适应边界框?

c - strtok 和 while 循环终止问题

C - 如何按子字符串拆分字符串

c - 将 int 数组附加到 c : 中的字符串

c - 扫描字符串中的字符串

c - for 循环没有考虑执行的最后一个循环

c++ - 如何在 Visual C++ 中创建 ActiveX DLL

c - Strtok 只输出字符串的一部分