2013-08-04 56 views
0

我試圖建立它運行在C語言編寫的命令行程序看起來像這樣:循環不能停止

int main(void){ 

    char code[25]; 
    char *fullCmd; 
    char *command; 
    char *extraCmd; 

    bool stop = false; 
    int loop = 1; 

    while (loop == 1){ 

     printf("C:\\>"); 
     scanf("%[^\n]",code); 

     fullCmd = strdup(code); 
     command = strtok(fullCmd, " "); 
     extraCmd = strtok(NULL, " "); 
     handStatement(code, command, extraCmd); 

     if(strcmp(command,"exit\n") == 0 || strcmp(command, "quit\n") == 0){ 
      loop = 0; 
      printf("Program Terminated\n"); 
     } 
    } 

    return 0; 
} 

HandStatement()是我的把手。但是這裏的問題是,執行handStatement()時while循環不會停止輸入另一個命令。如果我不使用時,我可以一次執行一個命令。

+0

消息「程序終止」曾經打印到屏幕上嗎? –

回答

3

您不需要在strcmp調用中跟蹤\n個字符。

if(strcmp(command,"exit") == 0 || strcmp(command, "quit") == 0){ 
     loop = 0; 
     printf("Program Terminated\n"); 
    } 

此外,您還需要從標準輸入刷新換行符:

while (loop == 1){ 
    printf("C:\\>"); 
    scanf("%[^\n]",code); 
    fullCmd = strdup(code); 
    command = strtok(fullCmd, " "); 
    extraCmd = strtok(NULL, " "); 
    handStatement(code, command, extraCmd); 
    if(strcmp(command,"exit") == 0 || strcmp(command, "quit") == 0){ 
     loop = 0; 
     printf("Program Terminated\n"); 
    } 
    /* Flush whitespace from stdin buffer */ 
    while(getchar() != '\n'); 
} 
+0

謝謝!是工作!謝謝! – Thangnv

0

如果您從您的代碼中的 '\ n',它會工作。除非您的終止字符已被更改,否則實際上不會將換行符放入字符串中,因此您的strcmp()將始終返回不相等。