这是我的代码,当只有一个单词之间没有空格或任何东西时(比如enter…),系统调用就会工作。
例如,当我使用“pwd”时,调用有效,但当我使用类似于ls -l
或“cd file1 file2”的内容时,它会删除第一个字符,并且不考虑空格后的任何内容。
所以当我写“cd file1 file2”时,只剩下“cd”的“d”。我能做些什么来阻止它?
#include <stdlib.h>
#include <stdio.h>
#include "Expert_mode.h"
void Expert_mode()
{
printf("Your are now in Expert mode, You are using a basic Shell (good luck) \nWe added the commands 'read_history', 'leave' and 'Easter_egg'. \n");
int a = 0;
while(a == 0)
{
char* line;
getchar();
printf("Choose a command : \n");
line = malloc(100*sizeof(char));
fgets(line, 100, stdin);
if(strcoll(line, "leave") == 0)
{
a = 1;
}
else if(strcoll(line, "read_history") == 0)
{
//read_history();
}
else if(strcoll(line, "Easter_egg") == 0)
{
// Easter_egg();
}
else
{
system(line);
}
}
}
最佳答案
这是因为你在打电话之前先打了个电话。因此它使用第一个字符,而getchar();
只读取其余的输入。把它取下来。
另外,请注意,如果缓冲区空间可用,fgets()
也会读取后面的换行符。你会想修剪它的。
您可以使用fgets()
删除换行符(如果存在):
fgets(line, 100, stdin);
char *p = strchr(line, '\n');
if (p) *p = 0;
关于c - fgets函数未读取输入中的第一个字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34319852/