2015-12-16 63 views
0

這裏是我的代碼和系統調用,當只有一個單詞之間沒有空格或任何內容(如enter ...)時。fgets函數不讀取輸入中的第一個字符

例如,當我用「PWD」的號召作品,但是當我使用類似ls -l或讓我們說「CD文件1文件2」,它會清除第一個字符,並沒有考慮到空間後帳戶什麼。

所以當我寫「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); 
     } 
    } 
} 
+0

如果你要分配一個固定大小的緩衝區,爲什麼不使用數組?那麼你將不會有內存泄漏。 –

回答

3

這是因爲你有getchar();電話fgets()電話。所以它消耗第一個字符,只有其餘的輸入被fgets()讀取。去掉它。

此外,請注意,fgets()也會讀取尾隨換行符,如果緩衝區空間可用。你會想修剪它。

您可以使用strchr()刪除換行符,如果存在的話:

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

非常感謝你^^但我如何使用你寫的代碼以及爲什麼?對不起,愚蠢的問題我是一個相當新手的編碼 –

+0

@ LucaS-c只需在你的代碼中fgets調用後複製粘貼我的答案中的最後2行。就是這麼簡單:) –

+0

非常感謝,我明白了這一點現在我覺得很愚蠢> –

相關問題