scanf和带有c字符串的strcmp [英] scanf and strcmp with c string

查看:100
本文介绍了scanf和带有c字符串的strcmp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一个很好的关于如何使用strcmp的示例,但它仅能正常工作与fgets(),我需要使其与scanf一起使用。所以,这是代码:

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;
}

即使我输入正确的answear(苹果),它也会停留在循环并不断询问我最喜欢的水果是什么...我猜测它与未在ans [80]上写的字符有关(我需要它是最大80chars的char数组)。我没有得到这个...

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...

谢谢。

推荐答案

Scanf将忽略 \n,因此您应该初始化 char fruit [] = apple ,因为ans永远不会以'\n'结尾。

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

PS:scanf的解释:任意数量的非空白字符,在找到的第一个空白字符处停止。在存储序列的末尾会自动添加一个终止的空字符。

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.

这篇关于scanf和带有c字符串的strcmp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆