首页 > 解决方案 > 如何在 C 中使用 if 语句?

问题描述

我试图制作一个类似于聊天机器人的简单代码,但我的代码遇到了问题,有人可以帮我解决这个问题吗?

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

int main() {
    char y[100];
    char w[100];
    char x[10] = "good";
    char z[10] = "bad";
    
    printf("Hi, what is your name?\n");
    scanf("%s", y);
    printf("nice to meet you %s, how is your day so far?\n", y);
    scanf ("%s", w);
    if(strstr(y, x) != NULL) {
        printf("Oh, whats wrong?\n");
        scanf("%s", w);
        printf("Oh, I hope your day gets better.");
    }else if(strstr(y, z) != NULL) {
        printf("thats good!");
    }else {
        printf("ERROR: invalid input");
    }
    
    return 0;
}

这是我得到的输出,它确实使用了一些用户输入,所以请记住这一点。

Hi, what is your name?
seth
nice to meet you seth, how is your day so far?
good
ERROR: invalid input

标签: cchatbot

解决方案


有一些错位的变量。

首先,您将用户输入存储到变量 w 中,但您没有在比较中使用该变量。其次,您没有将其与输入的正确变量进行比较。

以下是注释掉旧行的更正。


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

int main() {
    char y[100];
    char w[100];
    char x[10] = "good";
    char z[10] = "bad";
    
    printf("Hi, what is your name?\n");
    scanf("%s", y);
    printf("nice to meet you %s, how is your day so far?\n", y);
    scanf ("%s", w);
    //if(strstr(y, x) != NULL) {
    if(strstr(w, z) != NULL) {
        printf("Oh, whats wrong?\n");
        scanf("%s", w);
        printf("Oh, I hope your day gets better.");
    //}else if(strstr(y, z) != NULL) {
    }else if(strstr(w, x) != NULL) {
        printf("thats good!");
    }else {
        printf("ERROR: invalid input");
    }
    
    return 0;
}


推荐阅读