do while循环不适用于C中的字符串比较

时间:2016-09-25 19:07:42

标签: c

我对C编程很陌生,所以请耐心等待我。下面是我的C语言代码。根据我的知识应该工作,但当我进入“退出”然后根据我的逻辑它应该工作。它不是。好吧,让我知道我做错了什么。

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h> 
#include <stdbool.h>

int main () {
char command[50];

do{
    int  pid ;
    char bin_dir[100]     ;
    char sbin_dir[100]    ;
    command[50] = '\0';    

    printf("\n get input to execute command: ");
    fgets (command, 100, stdin);

    printf("\n Entered command is : %s " ,command);

    strcpy(sbin_dir,"/sbin/");
    strcpy(bin_dir,"/bin/");

    strcat(bin_dir  ,command);
    strcat(sbin_dir ,command);

     if( access( bin_dir, F_OK ) != -1 ) {
         printf(" command found in bin Directory \n");
       } else if (access( sbin_dir, F_OK ) != -1 ) {
         printf(" command found in sbin Directory \n");
       }else {
         printf("command not found \n");
       }

    }while(strcmp (command, "exit") == 0);
   return 0;
}

1 个答案:

答案 0 :(得分:4)

  1. 循环必须为while (strcmp(...) != 0),而不是== 0
  2. 我认为fgets会在最后读取LF行 - 比较strcmp(command,"exit\n")
  3. PS:command[50] = '\0'错了。必须为command[49] = 0或更高memset(command, 0, sizeof command)

    PS2:fgets (command, 100, stdin)几乎没有问题 - command是50个字节的数组,fgets最多允许100个。使用fgets (command, sizeof command, stdin)