gpt4 book ai didi

c - strtok 不返回任何值

转载 作者:太空狗 更新时间:2023-10-29 15:56:30 28 4
gpt4 key购买 nike

我想编写一个程序,将带有数字 ("1 2 3") 的字符串转换为整数数组。但是 strtok() 不返回值。为什么不?我的控制台输出只是空的。

编辑:我没有收到任何错误消息。

这是我的代码:

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

int* string_to_array(char * string, int * myArray);

int main(void) {
int* myArray = 0;
myArray = (int*) malloc(10 * sizeof(int));
myArray = string_to_array("1 2 3 4", myArray);

printf("result: %d\n", myArray[0]);
printf("result: %d\n", myArray[1]);
return 0;
}

int* string_to_array(char * string, int * myArray){
char delimiter[] = " ";
char *ptr;
char *ptr2;
long ret;

printf("string_to_array() was called.\n");
printf("string is: %s\n", string);

ptr = strtok(string, delimiter); // here is the problem
printf("strtok done; ptr: %s\n", ptr);

int index = 0;
while(ptr != NULL) {
ret = strtol(ptr, &ptr2, 10);
printf("ret: %d\n", ret);
myArray[index] = ret;
ptr = strtok(NULL, delimiter);
index++;
}

return myArray;
}

最佳答案

由于 strtol 用于解析值,因此使用 ptr2 遍历 string。转换后,ptr2 将指向转换值后的下一个字符。将其用作下一次转换的起点。可以使用 strtol 进行更多错误检查。

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

int* string_to_array(char * string, int * myArray);

int main(void) {
int* myArray = 0;
myArray = (int*) malloc(10 * sizeof(int));
myArray = string_to_array("1 2 3 4", myArray);

printf("result: %d\n", myArray[0]);
printf("result: %d\n", myArray[1]);
return 0;
}

int* string_to_array(char * string, int * myArray){
char *ptr;
char *ptr2;
long ret;

printf("string_to_array() was called.\n");
printf("string is: %s\n", string);

ptr = string;

int index = 0;
while(*ptr) {
ret = strtol(ptr, &ptr2, 10);
printf("ret: %ld\n", ret);
myArray[index] = ret;
ptr = ptr2;
index++;
}

return myArray;
}

关于c - strtok 不返回任何值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57969717/

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