为什么strcmp在这种情况下不返回0?

var*_*tis 2 c strcmp

所以我从一个文件中逐个读取字符:

char temp[3];

temp[0] = nextchar;
printf("%c",temp[0]); //prints %

temp[1] = nextchar = fgetc(srcptr);
printf("%c",temp[1]); //prints 2

temp[2] = nextchar = fgetc(srcptr);
printf("%c",temp[2]); //prints 0

if(strcmp(temp, "%20") == 0) { printf("%s","blahblah"); }
Run Code Online (Sandbox Code Playgroud)

理想情况下,这应该在最后打印"blahblah".但事实并非如此.那么为什么strcmp返回0,更重要的是:我该如何修复呢?

Ed *_*eal 9

你需要null终止temp.

编辑

更改char temp[3];char temp[4]; temp[3] = 0;


Dan*_*ger 6

memcmp改用,因为strcmp期望两个字符串都被'\0'终止(并且temp不是):

if(memcmp(temp, "%20", sizeof(temp)) == 0) { printf("%s","blahblah"); }
Run Code Online (Sandbox Code Playgroud)