ImranNaqvi ImranNaqvi - 1 year ago 90
C Question

do While loop not working for string comparing in C

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.

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

int main () {
char command[50];

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);


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;

Answer Source
  1. The loop must be while (strcmp(...) != 0), not == 0.
  2. I think fgets will read line with LF at the end - compare strcmp(command,"exit\n").

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

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download