fgets 函数未读取输入中的第一个字符

fgets function is not reading the first character in the input

这是我的代码,系统调用在只有一个单词且没有 space 或任何介于两者之间的单词(如输入...)时起作用。

例如,当我使用 "pwd" 时,调用有效,但是当我使用 ls -l 之类的东西时,或者说 "cd file1 file2" 它会删除第一个字符,并且不会考虑任何内容在 space.

之后

所以当我写"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);
        }
    }
}

这是因为您在 fgets() 调用之前 getchar(); 调用了 。所以它消耗了第一个字符,只有输入的其余部分被 fgets() 读取。删除它。

另外请注意,如果缓冲区 space 可用,fgets() 也会读取结尾的换行符。你会想要 trim 它。

您可以使用 strchr() 删除换行符,如果存在:

fgets(line, 100, stdin);
char *p = strchr(line, '\n');
if (p) *p = 0;