我无法将char拆分成单独的单词并打印出来

我试图将用户的输入拆分为单独的单词,然后将每个单词打印在换行符上。

我有一个函数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]);
    }
  }
}
fandly_jw 回答:我无法将char拆分成单独的单词并打印出来

有很多问题:

这就是您想要的。这些评论解释了问题所在:

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行代码)

本文链接:https://www.f2er.com/3065514.html

大家都在问