You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用strtok()获取的第二个令牌?C语言代码问题求助

问题分析与解决方案

问题根源

你的代码存在两个核心问题,导致cd分支无法正常执行或执行异常:

  1. 换行符未处理:fgets会将输入末尾的换行符\n一并存入数组,若仅用空格作为strtok的分隔符,第二个令牌会带上\n,导致chdir("..\n")因无效路径失败。
  2. 循环逻辑错误:内层while会迭代所有令牌,处理cd时拿到第二个令牌后,循环会继续判断该令牌,进而进入else分支打印错误信息,干扰正常流程。

修正后的代码

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

int main(){
    char input[256];
    while(1) {
        fgets(input, 256, stdin);
        
        // 移除fgets读取的末尾换行符
        size_t len = strlen(input);
        if (len > 0 && input[len-1] == '\n') {
            input[len-1] = '\0';
        }

        char *token = strtok(input, " ");
        if (token == NULL) {
            continue; // 空输入直接跳过
        }

        if (strcmp(token, "exit") == 0) {
            exit(EXIT_SUCCESS);
        } 
        else if (strcmp(token, "cd") == 0) {
            char *dir = strtok(NULL, " ");
            if (dir == NULL) {
                printf("cd: missing directory\n");
            } else {
                if (chdir(dir) != 0) {
                    perror("cd"); // 打印chdir失败的系统错误信息
                }
            }
        } 
        else {
            printf("Command not found.\n");
        }
    }
    return 0;
}

关键调整说明

  • 处理换行符:通过strlen定位并移除输入末尾的换行符,避免令牌包含无效字符。
  • 简化循环逻辑:移除内层while,因为我们仅需处理命令(第一个令牌)和对应参数(第二个令牌),无需遍历所有令牌。
  • 更严谨的字符串比较:用strcmp替代strncmp,避免误匹配cdxyz这类以cd开头的错误命令。
  • 添加错误处理:针对仅输入cd无参数的情况给出提示,同时在chdir失败时打印具体错误原因。

内容的提问来源于stack exchange,提问作者CJF

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 12:45:46