[英]strncmp doesn't return 0 on equal strings
Shouldn't the strncmp("end",input,3) == 0
return 0 if the input is end?如果
strncmp("end",input,3) == 0
返回 0 吗? It returns a number > 0 though.但是它返回一个 > 0 的数字。
#include <stdio.h>
int main(void) {
char *strArray[100];
int strLengths[100];
char input[100];
int flag = 0;
do {
scanf("%c",&input);
if(strncmp("end",input,3) == 0) {
printf("end\n");
}
printf("%d\n",strncmp("end",input,3));
} while(flag !=0);
return 0;
}
This这个
scanf("%c",&input);
reads just a single char
- maybe.只读取一个
char
- 也许。 It's wrong - pay attention to the errors and warnings you get from your compiler.这是错误的 - 注意你从编译器中得到的错误和警告。
The format specifier is not correct - %c
means scanf()
will attempt to read a char
, but you're passing the address of a char[100]
array.格式说明符不正确 -
%c
表示scanf()
将尝试读取char
,但您传递的是char[100]
数组的地址。 That's undefined behavior, so anything might happen.这是未定义的行为,所以任何事情都可能发生。
You're also not checking the return value to see if scanf()
worked at all, so you don't really know what's in input
.您也没有检查返回值以查看
scanf()
有效,因此您并不真正知道input
。
In your case, the strings compared with strncmp("end",input,3) == 0
will never match as input
will contains only one character.在您的情况下,与
strncmp("end",input,3) == 0
相比的字符串永远不会匹配,因为input
将仅包含一个字符。
The call scanf("%c",&input);
调用
scanf("%c",&input);
will read only the 1st character entered, and will store it in input
将只读取输入的第一个字符,并将其存储在
input
#include <stdio.h>
int main(void) {
char *strArray[100];
int strLengths[100];
char input[100];
int flag = 0;
do {
scanf("%s",input); //%c is for a single char and %s is for strings.
if(strncmp("end",input,3) == 0) {
printf("end\n");
}
printf("%d\n",strncmp("end",input,3));
} while(flag !=0);
return 0;
}
Next time print the input before continuing to confirm that you are doing it correct.下次在继续确认您正确执行之前打印输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.