using fgets and strcmp in C [duplicate]

╄→尐↘猪︶ㄣ 提交于 2019-12-02 11:11:19

Note two things in your code:

  1. fgets keeps the trailing '\n'. the associated char in fruit should be replaced with a '\0' before comparing with the string "apple".
  2. strcmp return 0 when two strings are the same, so the if clause should be changed based on what you mean.(The fruit and "apple" be equivalent in the if clause)
  3. Standard usage of C main function is int main(){ return 0;}

The revised code:

#include <stdio.h>
#include <string.h>

char fruit[100];

int main() {
    printf("What is your favorite fruit?\n");
    fgets (fruit, 100, stdin);
    fruit[strlen(fruit)-1] = '\0';
    if (strcmp(fruit, "apple") == 0) {
        printf("Watch out for worms!\n");
    }
    else {
        printf("You should have an apple instead.\n");
    }
    return 0;
}
Sarat

Change the if condition to the following:

if(strcmp(fruit,"apple") == 0)

strcmp returns 0 strings if match. You should always compare the result using == operator

strcmp returns 0 if the inputs match, some value>0 if the left is "greater" than the right, some value<0 if the left is "lesser" than the right. So usually you want to simply test for equality with strcmp(...)==0. But there is also the clever version: !strcmp(...). Even if you don't use this style, it's useful to learn to recognize it.

And remember that fgets does not remove the newline character '\n' from the string.

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