简体   繁体   English

scanf和strcmp with c string

[英]scanf and strcmp with c string

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. 我找到了一个很好的例子 ,说明如何使用strcmp,但它只适用于fgets(),我需要使用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). 即使我写了正确的answear(“苹果”),它仍然留在循环中并一直问我最喜欢的水果......我猜它与没有写在ans [80]的字符有关。 (我需要它是一个最多80chars的char数组)。 I'm not getting this... 我不是这个......

Thanks in advance. 提前致谢。

Scanf will ignore "\\n", so you should init char fruit[] = "apple" , since ans will never end with '\\n'. Scanf将忽略“\\ n”,因此你应该初始化char fruit[] = "apple" ,因为ans永远不会以'\\ n'结尾。

PS: An explain for scanf: Any number of non-whitespace characters, stopping at the first whitespace character found. PS:scanf的解释:任意数量的非空白字符,停在找到的第一个空白字符处。 A terminating null character is automatically added at the end of the stored sequence. 在存储序列的末尾自动添加终止空字符。

scanf() does not write the trailing newline character(s) into ans . scanf()不会将尾部换行符写入ans strcmp() does consider newline characters in its comparison, so it's not matching your literal, which includes the newline. strcmp()确实在其比较中考虑了换行符,因此它与您的文字(包括换行符)不匹配。

"scanf" does take newline "\\n" character as input. “scanf”确实将换行符“\\ n”作为输入。 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). 如果你想要两个字符串相等,你需要从第一个字符串中删除换行符“\\ n”(“apple”很好)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM