用strtok分割一个C字符串

问题描述:

我正在寻找一种方法来以特定方式从一个C字符串中提取strtok的值。我有一个C字符串,我需要拿出一个数字,然后将其转换为双精度。我可以很容易地转换为double,但是我需要它仅根据请求的“度数”来提取一个值。基本上0度会将第一个值拉出字符串。由于我使用的循环,我当前的代码已经遍历整个C字符串。有没有办法只针对一个具体的价值,并让它把这个双重价值拉出来?用strtok分割一个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

如果你使用C++,为什么不使用'std :: sting'和'std :: stringstream'?例如:http://*.com/questions/236129/split-a-string-in-c – NathanOliver

+0

你可以举一个你要求的例子 – Sniper

+0

我需要使用C字符串。我发现如何让它工作。 – ajn678

为了简单起见,您问了如何确定标记器中的第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? 
}