2013-09-23 116 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); 
    } 
}