Testing string equality issue

匿名 (未验证) 提交于 2019-12-03 01:09:02

问题:

Haven't programmed in C in a while, so I'm surely missing something here but I can't figure out what it is.

I have two strings, as shown below:

char toMatch[] = "--exit--"; char entry[1024]; 

Through this program, I have a while loop that accepts user input to modify the string entry throughout the program. I would like to exit this while loop when entry equals toMatch.

I thought this was easy to do with the strcmp function, but it's not working for some reason. Originally I had this:

while(strcmp(entry, toMatch) != 0) {     // accept user input here to modify entry } 

However, this didn't work. So I added one line of code to clear the contents of entry before accepting user input again:

while(strcmp(entry, toMatch) != 0) {     memset(entry, 0, sizeof(entry));     // accept user input here to modify entry } 

This doesn't work either. I need to have entry be this long, because the entry of the user can be any length smaller than this. I have no idea why strcmp() is not working, so I think I'm missing something that should be obvious.

回答1:

Using strcmp() is easy enough if you always write the comparison explicitly with zero:

  • strcmp(a, b) == 0 for equality
  • strcmp(a, b) != 0 for inequality
  • strcmp(a, b) >= 0 for a sorts equal to or after b
  • strcmp(a, b) > 0 for a sorts after b
  • strcmp(a, b) <= 0 for a sorts equal to or before b
  • strcmp(a, b) < 0 for a sorts before b

If you're having problems matching "--exit--" against your input, did you strip leading blanks, trailing blanks, trailing newline (especially the latter if you read the input with fgets()). What does this show:

printf("[[%s]]\n", entry); 

The square brackets show you where the program thinks the ends of the string are.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!