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;
}
如果你使用C++,爲什麼不使用'std :: sting'和'std :: stringstream'?例如:http://stackoverflow.com/questions/236129/split-a-string-in-c – NathanOliver
你可以舉一個你要求的例子 – Sniper
我需要使用C字符串。我發現如何讓它工作。 – ajn678