首页 > 解决方案 > 当用户在C中输入“退出”时如何让程序终止

问题描述

当我输入“退出”时,程序似乎并没有从我下面的代码中终止;当用户键入“退出”时,是否有我遗漏的东西或者有更好的方法来终止程序?

在我的代码中,您还可以看到它在 EOF 发生时终止,这可以正常工作,只是在我输入“exit”时它不会终止。

我的代码:

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

标签: c

解决方案


输入==“退出”

是错的。应该是strcmp(input,"exit")==0,否则你将输入字符串的地址与内存中字符串“exit”的地址进行比较,而不是内容。

确保先从通话中删除换行符fgets,或使用strncmp(input, "exit", 4)


推荐阅读