2017-04-26 92 views
1

我正在尋找一種方法來以特定方式從一個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://stackoverflow.com/questions/236129/split-a-string-in-c – NathanOliver

+0

你可以舉一個你要求的例子 – Sniper

+0

我需要使用C字符串。我發現如何讓它工作。 – ajn678

回答

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