I'm new to C, I have lines of code look like this:
char user[16];
fgets(user,16,stdin);
I typed "zeyang" on the keyboard, and I have another code:
char pwname[1000];
pwname="zeyang";
Then I use strcmp
to compare user and pwname:
strcmp(user, pwname);
The return value is a negative number, I expect it to be 0, because they are all "zeyang". Why it isn't 0?
fgets
includes the typed newline if there's room. You're comparing "zeyang\\n"
with "zeyang"
. From the fgets(3)
man page :
The newline, if any, is retained.
来自stdin的第一个字符串包含一个附加的换行符。
The problem is that the sentence you enter will be terminated by a new line character. (I guess you pressed ENTER when you have finished to insert characters. :D
In this case I would use strncmp :
strncmp(user,pwname,strlen(pwname));
This code won't compare the new line character.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.