C 比较输入中的字符串
我试图请求用户输入,我需要这样做,如果用户键入C 比较输入中的字符串,c,C,我试图请求用户输入,我需要这样做,如果用户键入退出,它就会终止程序 以下是我所拥有的,但由于某些原因它不起作用: int main(void) { char input[100]; printf("Enter: "); while(fgets(input, 100, stdin)) { if(strcmp("exit", input) == 0) { exit(0); } } } 为什么不退出?你做的一切几乎都是对的 问题是“fgets()”返回
退出
,它就会终止程序
以下是我所拥有的,但由于某些原因它不起作用:
int main(void) {
char input[100];
printf("Enter: ");
while(fgets(input, 100, stdin)) {
if(strcmp("exit", input) == 0) {
exit(0);
}
}
}
为什么不退出?你做的一切几乎都是对的
问题是“fgets()”返回尾随的换行符,而“enter\n”!=“进入”
建议:
改用:
if(strncmp(“enter”,input,5)=0{…}
,因为输入包含一个尾随'\n'
while(fgets(input, 100, stdin)) {
char *p=strchr(input, '\n');
if(p!=NULL){
*p=0x0;
]
if(strcmp("exit", input) == 0) {
exit(0);
}
使用scanf()
:
谢谢,我工作了。此外,如果输入需要值之间的逗号(例如,输入可能是
test,15
),我如何将这些值分离并放入其他变量中?
while(scanf("%s", input)) {
printf("input : %s\n", input);
if(strcmp("exit", input) == 0) {
exit(0);
}
}