在C中使用fgets和strcmp [英] using fgets and strcmp in C

查看:55
本文介绍了在C中使用fgets和strcmp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从用户那里获取字符串输入,然后根据他们输入的输入来运行不同的功能.

I'm trying to get a string input from the user and then run different functions depending on the input they've entered.

例如,我问,您最喜欢的水果是什么?"我希望程序根据输入的内容进行注释...我不确定如何执行此操作.这是我到目前为止的内容:

For example, say I asked, "What is your favorite fruit?" and I want the program to comment depending on what they enter...I'm not sure how to do this. Here's what I have so far:

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

char fruit[100];

main() {
    printf("What is your favorite fruit?\n");
    fgets (fruit, 100, stdin);
    if (strcmp(fruit, "apple")) {
        printf("Watch out for worms!\n");
    }
    else {
        printf("You should have an apple instead.\n");
        }

}

当我运行程序时,无论输入什么,它都不会执行else语句.

When I run the program, no matter what I enter, it never does the else statement.

感谢您的帮助!

推荐答案

请注意代码中的两件事:

Note two things in your code:

  1. fgets保留结尾的"\ n".与字符串"apple"进行比较之前,应将水果中关联的字符替换为"\ 0".
  2. 当两个字符串相同时,strcmp返回0,因此应根据您的意思更改if子句.(if子句中的fruit和"apple"等效)
  3. C main函数的标准用法是 int main(){return 0;}

修改后的代码:

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

这篇关于在C中使用fgets和strcmp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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