Search code examples
cfgetsstrtokstrcmp

how can I fix this token comparison on input from fgets in c


I'm having an issue where I enter for example, "exit l" and it works for the command which is incorrect and if I enter exit it doesn't work I check to see if the next token is empty but I don't know if I'm doing it right. I think if I check for the next token I should get a 0 or in another check style NULL;

while (exitloop != 1){ // do the user commands
    //TODO fix for mem issue
    char userinput[1000];
    char delim[4] = " ";
    printf("[**]Enter Command: ");
    fgets(userinput, 1000, stdin);
    int userinputlen = strlen(userinput);
    userinput[userinputlen] = '\0';
    char first_token[5];
    char second_token[100];
    char extra[100];

    strcpy(first_token, strtok(userinput, " "));
    first_token[strlen(first_token)] = '\0';
    printf("%s", first_token);

    if (strcmp(first_token, "exit") == 0) { // exit "done"
        printf("igot in exit");
        if (strtok(0,delim) == 0){ // test
            perror("[-] input for exit incorrect....\n");
        } else {
            const char quit = 'Q';
            char cmdbuff[1];
            if (send(socketfd, &quit, 1, 0) < 0){
                perror("[-] Error in sending request.....\n");
            } else {
                recv(socketfd, cmdbuff, sizeof(cmdbuff),0);
                if (strcmp(&cmdbuff[0],"A") !=0) {
                    exitloop = 0;
                    perror("[-] Erorr exit failed on server side....\n");
                } else {
                    printf("[+] Sucessful exit...\n");
                    exitloop = 1;
                }
            }
        }
    } else if (strcmp(first_token,"ls") == 0) { // ls

Solution

  • I fixed this problem by replacing the \n with \0 on a while loop