scanf and strcmp with c string

烂漫一生 提交于 2019-12-20 04:04:10

问题


I found a nice example of how to use strcmp, but it's only working with fgets(), and i need to make it work with scanf. So, here's the code:

int main(void) {
char fruit[] = "apple\n";
  char ans[80];
  do {
     printf ("Guess my favorite fruit? ");
     scanf ("%s",ans);
  } while (strcmp (fruit, ans) != 0);
  puts ("Correct answer!");
  return 0;
}

Even when I write the correct answear ("apple") it stays in the loop and keeps asking me what is the favorite fruit... I'm guessing it has something to do with the chars that are not written at ans[80](I need it to be a char array with 80chars at max). I'm not getting this...

Thanks in advance.


回答1:


Scanf will ignore "\n", so you should init char fruit[] = "apple", since ans will never end with '\n'.

P.S: An explain for scanf: Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.




回答2:


scanf() does not write the trailing newline character(s) into ans. strcmp() does consider newline characters in its comparison, so it's not matching your literal, which includes the newline.




回答3:


"scanf" does take newline "\n" character as input. So you are not able to equal the both strings. if you want to equal both strings you need to remove newline"\n" form the first string ("apple" is fine).



来源:https://stackoverflow.com/questions/20792246/scanf-and-strcmp-with-c-string

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