【发布时间】:2021-02-10 03:01:24
【问题描述】:
我正在尝试为操作系统类编写 Linux shell 替代品,但无法解析输入字符串。我可以读取字符串输入的第一行,但是一旦到达任何空格分隔符,它就会完全跳过其他所有内容并进入新的提示符。下面是我想要处理的代码。
while(1){
//Flush I/O streams to prevent duplicate '#' printing each new line
fflush(stdout);
fflush(stdin);
printf("# ");
//Take in the input and store it in an auxiliary variable.
scanf("%s", input);
strcpy(commandInput, input);
char *ptr = strtok(commandInput, delimiter); //Parse the command and check what it is below.
if(strcmp(commandInput, "byebye") == 0){ //End the shell program
exit(1);
} else if(strcmp(commandInput, "whereami") == 0){ //Get the current working directory
getCurrentDirectory();
break;
} else if(strcmp(commandInput, "movetodir") == 0){
//Store the new directory name once returned
strcpy(currentDirectory, changeDirectory());
break;
} else {
//Handles any invalid input strings of any length
printf("%s\n", ptr);
while(ptr != NULL){
printf("%s\n", ptr);
ptr = strtok(NULL, delimiter);
}
}
}
例如,下面是我输入一个在标记之间有空格的随机字符串时得到的输出:
# hi there
hi
hi
# byebye
它也应该在“那里”打印出来,但它永远不会到达它。任何帮助将不胜感激!
【问题讨论】:
-
不要不在 input 流上执行
fflush——它会做一些古怪的事情,所以请消除fflush(stdin); -
这是做什么的?我本以为大部分时间都清除输入和输出流会很好。
-
输入流没用/UB。它的唯一有效用途是在输出流上强制 缓冲 输出。充其量,它什么也不做。在最坏的情况下,它会破坏输入缓冲区。有很多 SO 问题/答案可以解释原因。另见
man fflush