我试图将用户的输入拆分为单独的单词,然后将每个单词打印在换行符上。
我有一个函数split()
,该函数尝试使用strtok()
方法拆分每个单词。当我尝试遍历Main()
中的单词以打印它们时,根本没有。
编译后,出现两个错误(看起来很难看,无法粘贴到其中)。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 10
#define SIZE 256
char *read_line(char *buf, size_t sz) {
printf("> ");
fgets(buf, sz, stdin);
buf[strcspn(buf, "\n")] = 0;
return buf;
}
void split(char *buf, char *words[], size_t max) {
char *temp = strtok(buf, " ");
for (int i = 0; words[0] != '\0'; i++) {
strcpy(words[i], temp);
temp = strtok(NULL, buf);
}
}
int main(int argc, char **argv) {
char *buf = malloc(SIZE);
char *words = malloc(MAX * sizeof(char));
while(1) {
char *input = read_line(buf, SIZE);
split(input, words, MAX);
for (int i = 0; words[i] != '\0'; i++) {
printf("%s\n", words[i]);
}
}
}
答案 0 :(得分:1)
有很多问题:
这就是您想要的。这些评论解释了问题所在:
void split(char* buf, char* words[], size_t max) {
char* temp = strtok(buf, " ");
int i = 0;
while (temp != NULL) // wrong usage of strtok
{
words[i++] = strdup(temp); // words[i] points nowhere, you need to allocate memory
temp = strtok(NULL, " "); // wrong usage of strtok
}
words[i] = NULL; // you didn't terminate the words array
}
int main(int argc, char** argv) {
char* buf = malloc(SIZE); // this could be "char buf[SIZE];". It's not wrong
// but there's no need for dynamically allocating memory here
char** words = malloc(MAX * sizeof(char*)); // you need to allocate pointers to char, not char
while (1) {
char* input = read_line(buf, SIZE);
split(input, words, MAX);
for (int i = 0; words[i] != NULL; i++) { // you need to check for the NULL pointer
printf("%s\n", words[i]); // not the NUL char
}
}
}
仍有改进的空间,
split
函数不会检查max
, strdup
在您的平台上可能不可用,因此您可能需要自己实现(基本3行代码)