繁体   English   中英

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

[英]do While loop not working for string comparing in 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. 循环必须是while (strcmp(...) != 0) ,而不是== 0
  2. 我认为fgets会在最后读取带有 LF 的行 - 比较strcmp(command,"exit\\n")

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM