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

时间:2022-04-26 18:14:29

I'm very new to C Programming so kindly bear with me . Below is my C language code . which according to my knowledge should work but when i enter "exit" then according to my logic it should work . which it ain't .Kindly let me what i'm doing wrong.

我对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 个解决方案

#1


4  

  1. The loop must be while (strcmp(...) != 0), not == 0.
  2. 循环必须是while(strcmp(...)!= 0),而不是== 0。
  3. I think fgets will read line with LF at the end - compare strcmp(command,"exit\n").
  4. 我认为fgets最后将读取LF行 - 比较strcmp(命令,“exit \ n”)。

PS: command[50] = '\0' is wrong. Must be command[49] = 0 or better memset(command, 0, sizeof command).

PS:命令[50] ='\ 0'错误。必须是命令[49] = 0或更好的memset(命令,0,sizeof命令)。

PS2: fgets (command, 100, stdin) has little problem - command is array of 50 bytes, and fgets allows up to 100. Use fgets (command, sizeof command, stdin).

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

#1


4  

  1. The loop must be while (strcmp(...) != 0), not == 0.
  2. 循环必须是while(strcmp(...)!= 0),而不是== 0。
  3. I think fgets will read line with LF at the end - compare strcmp(command,"exit\n").
  4. 我认为fgets最后将读取LF行 - 比较strcmp(命令,“exit \ n”)。

PS: command[50] = '\0' is wrong. Must be command[49] = 0 or better memset(command, 0, sizeof command).

PS:命令[50] ='\ 0'错误。必须是命令[49] = 0或更好的memset(命令,0,sizeof命令)。

PS2: fgets (command, 100, stdin) has little problem - command is array of 50 bytes, and fgets allows up to 100. Use fgets (command, sizeof command, stdin).

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