scanf and strcmp with c string

前端 未结 3 1810
南笙
南笙 2021-01-21 17:17

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) {
c         


        
相关标签:
3条回答
  • 2021-01-21 18:18

    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.

    0 讨论(0)
  • 2021-01-21 18:23

    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.

    0 讨论(0)
  • 2021-01-21 18:23

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

    0 讨论(0)
提交回复
热议问题