gpt4 book ai didi

c - 使用分隔符将字符串分隔为 double 组

转载 作者:太空宇宙 更新时间:2023-11-04 04:29:59 26 4
gpt4 key购买 nike

我想创建一个函数,从特定字符串返回 double 组。

我尝试了多种选择,但都没有成功

我有一个给定的函数 createWeightsArray,我需要填充它。还将给出 numofgrades,这很有帮助

字符串类似于:“30% 40% 50%”,我需要一个双数组 {0.3,0.4,0.5}

这是我最近的尝试:

double* createWeightsArray(char* str, int numOfGrades) {
double *gradesweight;
gradesweight = (double*)malloc(numOfGrades * sizeof(double));
int i = 0, n = 0;
while (*str != '\0') {
while (strchr("%", *str)) ++str;
if (*str == '\0') break;
*(gradesweight + n) = (atof(str) / 100);
n++;
str = strstr(str, "% ");
if (str == NULL) break;
*str = '\0';
++str;
}
return gradesweight;

我们将不胜感激

最佳答案

检查一下。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

double* str2double(char *string, int length)
{
int index = 0;
const char delimitor[2] = "% "; /* Delimintor, used the break the string */
char *token;
double *array = malloc(sizeof(double) * length);

if (array == NULL){
fprintf(stderr, "Failed to allocate memory \n");
return NULL;
}

/* get the first token */
token = strtok(string, delimitor);

/* walk through other tokens */
for( index=0; token != NULL && index < length ; index++)
{
array[index] = strtod(token, &token) / 100;
token = strtok(NULL, delimitor);
}
return array;
}

int main()
{
char str[] = "30% 40% 80% 60%";
double *ptr = str2double(str, 4);

if (ptr != NULL) {
for (int i = 0; i < 4; i++)
printf( "%f\n", ptr[i]);
}

return 0;
}

关于c - 使用分隔符将字符串分隔为 double 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37361094/

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