gpt4 book ai didi

C - 使用 strtok 将字符串数组拆分为字符数组

转载 作者:行者123 更新时间:2023-11-30 14:57:39 27 4
gpt4 key购买 nike

这是 my last question 的延续.

到目前为止,我已成功获取用户输入并将其存储到字符串中。例如,我把这个:

1:E 2:B 2:B 2:B 4:G

进入这个:1:E 2:B 2:B 2:B 4:G
这是一个字符串数组。

这是我接下来想做的,但它对我不起作用:1 E 2 B 2 B 2 B 4 G
其中每一个都是存储在字符数组中的字符。

这是我正常工作的代码块:

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

#define MAX_INPUT_SIZE ( (sizeof(char)*96) + (sizeof(int)*48) )

int main () {

char *input = malloc(MAX_INPUT_SIZE);

printf("Example input: 1:E 2:C 2:C 2:C 8:D\n");
printf("Your input:\n\n");

fgets(input, MAX_INPUT_SIZE, stdin);

// Removing newline
if ( (strlen(input) > 0) && (input[strlen(input) - 1] == '\n') )
input[strlen(input) - 1] = '\0';

int i = 0;
char *p = strtok(input, " ");
char *array[MAX_PAIRS];

while (p != NULL){
array[i++] = p;
p = strtok(NULL, " ");
}

// Checking the array
int j = 0;
for (j=0; j<i; j++) {
printf("\n %s", array[j]);
}

这段代码运行得很好。接下来是我当前正在使用的代码:

  int k = 0;
int l = 0;

char *letter = malloc( sizeof(char) * (i * 2) );

for (k=0; k<i; k++) {
char *q = strtok(array[k], ":");

while (q != NULL) {
letter[l++] = q;
q = strtok(NULL, ":");

}
}

// Checking the array
int m = 0;
for (m=0; m<l; m++) {
printf("\n %c", letter[m]);
}

return 0;
}

当我去检查数组时,它为我想要打印的每个字符打印一个垃圾符号。我不明白我在这里做错了什么。

最佳答案

letterchar 数组。
q 是一个char*

因此,letter[l++] = q 不会执行您想要的操作,因为您现在将 char* 存储到 char;我想编译器会发出一些关于截断的警告。

关于C - 使用 strtok 将字符串数组拆分为字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43751078/

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