strtok遇空格时无法返回更多token的问题求助
问题根源
你的问题根本不在strtok,而是**scanf("%30s", input)的读取逻辑**:
%s格式符会在遇到空格、换行、制表符这类空白字符时立刻停止读取。比如你输入apple, banana, cherry,input里只会存apple,,后面的banana, cherry根本没被读进程序,strtok自然只能处理第一个token。- 你看到的“去除空格的输出”其实是错觉——程序根本没读到空格后面的内容,只处理了空格前的部分。
修复方案
把读取输入的scanf换成fgets,它能读取整行内容(包括空格),注意要去掉fgets可能读入的换行符:
// 替换原来的scanf行 fgets(input, SIZE, stdin); // 去掉fgets读入的换行符(如果存在) input[strcspn(input, "\n")] = '\0';
额外问题提醒
你的代码里还缺了word结构体的定义,补上类似下面的代码才能正常编译:
typedef struct word { char value[30]; // 分配足够空间存储字符串 struct word *next; } word;
另外原代码每次循环都会多分配一个空节点,建议调整链表创建逻辑避免内存浪费:
word *head = NULL, *current = NULL; char *arr = strtok(input, ","); while (arr != NULL) { word *new_node = malloc(sizeof(word)); assert(new_node != NULL); strcpy(new_node->value, arr); new_node->next = NULL; if (head == NULL) { head = new_node; current = new_node; } else { current->next = new_node; current = new_node; } arr = strtok(NULL, ","); }
内容的提问来源于stack exchange,提问作者Davido
相关产品推荐
相关产品推荐

