Thangnv
Thangnv

Reputation: 815

Loop can't stop

I'm trying to build a program which runs in command line written in C looks like that:

int main(void){

    char code[25];
    char *fullCmd;
    char *command;
    char *extraCmd;

    bool stop = false;
    int loop = 1;

    while (loop == 1){

        printf("C:\\>");
        scanf("%[^\n]",code);

        fullCmd = strdup(code);
        command = strtok(fullCmd, " ");
        extraCmd = strtok(NULL, " ");
        handStatement(code, command, extraCmd); 

        if(strcmp(command,"exit\n") == 0 || strcmp(command, "quit\n") == 0){
            loop = 0;
            printf("Program Terminated\n");
        }
    }

    return 0;
}

HandStatement() is one of my handles. But problems in here is that the while loop won't stop for me to enter another command when handStatement() is executed. If I don't use while, I can execute one command at a time.

Upvotes: 0

Views: 145

Answers (2)

phyrrus9
phyrrus9

Reputation: 1467

If you remove the '\n' from your code, it will work. Unless your termination character has been changed, it will not actually place the newline character into the string and therefore your strcmp() will always return not equal.

Upvotes: 0

Nemanja Boric
Nemanja Boric

Reputation: 22177

You don't need trailing \n characters in your strcmp call.

    if(strcmp(command,"exit") == 0 || strcmp(command, "quit") == 0){
        loop = 0;
        printf("Program Terminated\n");
    }

Also, you need to flush newline characters from stdin:

while (loop == 1){
    printf("C:\\>");
    scanf("%[^\n]",code);
    fullCmd = strdup(code);
    command = strtok(fullCmd, " ");
    extraCmd = strtok(NULL, " ");
    handStatement(code, command, extraCmd);
    if(strcmp(command,"exit") == 0 || strcmp(command, "quit") == 0){
        loop = 0;
        printf("Program Terminated\n");
    }
   /* Flush whitespace from stdin buffer */
   while(getchar() != '\n');
}

Upvotes: 3

Related Questions