[英]C strtok() and strcmp() issues
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int args, char* argv[])
{
const int CBUFF = 1024;
char input[CBUFF];
char wkdir[CBUFF];
char* command;
printf("Welcome to MyShell...\n");
while(1)
{
getcwd(wkdir, CBUFF);
printf("%s ? ", wkdir);
fgets(input, CBUFF, stdin);
command = strtok(input, " ");
if(strcmp(command, "cd") == 0)
{
char* path;
path = strtok(NULL, " ");
if(chdir(path) != 0)
{
printf("ERROR: COULD NOT CHANGE DIRECTORY TO SPECIFIED PATH");
}
}
if(strcmp(command, "exit") == 0) break;
}
return 0;
}
我在 C 中創建一個非常簡單的命令C
時遇到了問題。 當我在指令后添加一個空格時,輸入也只會按照我想要的方式被讀取。 我知道這與我對strtok()
function 的不當使用有關,但我無法弄清楚我做錯了什么。 我已經閱讀了<string.h>
的文檔,結果一片空白。
我想要的行為:指令“exit”退出程序。 當前行為:必須在指令后添加空格才能正確解析,即。 輸入“exit”或“cd”。
您在緩沖區中留下了尾隨的換行符。 擺脫它。
char *got = fgets(input, CBUFF, stdin);
if (!got) return ; /* EOF -- treat like exit */
size_t gotlen = strlen(got);
if (got[gotlen] == '\n') got[gotlen] = 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.