4

When I type in "exit" the program doesn't seem to terminate from my code below; is there something I am missing or is there better way to terminate the program when the user types "exit"?

In my code you can also see it terminates when an EOF occurs this works properly, it just does not terminate when I type in "exit".

MY CODE:

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

int main () {
   char input[512];
   char * charp;
   int len = 0;

   printf("> ");
   if(fgets(input, 512, stdin) == 0 || input == "exit") {    /* reads in input from user no more than 512 chars including null terminator*/
     printf("exitting program");
       exit(0);
   }

   printf("You entered: %s", input);
   len = strlen(input);

    charp = strtok(input, "  ' '\t"); /* splits the string on delimiters space '' and tab*/
    while (charp != NULL) {
        printf("%s\n", charp);
        charp = strtok(NULL, "  ' '\t"); 
    }

   printf("The len of input = %d ", len);

   return(0);
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
program.exe
  • 451
  • 4
  • 12
  • `input == "exit"` does not do a string comparison but a comparison of the pointers to the first element. `"exit"` is a string literal and has a completely different address from the stack variable `input`. – flowit Jan 23 '21 at 18:33

1 Answers1

4

input == "exit"

Is wrong. It should be strcmp(input,"exit")==0, otherwise you compare the address of the inputted string to the address of the string "exit" in memory, not the contents.

Make sure you remove the newline from your fgets call first, or use strncmp(input, "exit", 4)

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
JCWasmx86
  • 3,473
  • 2
  • 11
  • 29