2013-09-23 113 views
0

我想要求用户输入,并且我需要这样做,以便如果用户键入exit,它会终止程序。来自输入的比较字符串

这里是我的,但它不工作由于某些原因:

int main(void) { 
    char input[100]; 

    printf("Enter: "); 

    while(fgets(input, 100, stdin)) { 
    if(strcmp("exit", input) == 0) { 
     exit(0); 
    } 
    } 
} 

为什么不退出?

回答

2

你正在尽一切努力几乎没错。

问题是,“fgets()”返回尾随的换行符,而“输入\ n”!=“enter”。

建议:

使用strncmp代替:if (strncmp ("enter", input, 5) == 0) {...}

+0

谢谢合作。另外,如果输入值之间需要逗号(例如,输入可能是'test,15'),我将如何分离这些值并将它们放入其他变量中? – user2805199

0

由于输入包含一个尾随 '\ n'

while(fgets(input, 100, stdin)) { 
    char *p=strchr(input, '\n'); 
    if(p!=NULL){ 
     *p=0x0; 
    ] 
    if(strcmp("exit", input) == 0) { 
     exit(0); 
    } 
0

使用scanf()

while(scanf("%s", input)) { 
    printf("input : %s\n", input); 
    if(strcmp("exit", input) == 0) { 
     exit(0); 
    } 
}