gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:02:34 25 4
gpt4 key购买 nike

我正在寻找一种以特定方式使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com