c - 如何在 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
解决方案
有一些错位的变量。
首先,您将用户输入存储到变量 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;
}
推荐阅读
- c# - 使用反射调用 ViewComponent
- javascript - 停止自动播放到轮播嵌入视频上的下一张幻灯片
- javascript - JavaScript throw 语句 *需要帮助*
- javascript - 移动鼠标时在 Firefox 中出现生涩的 javascript 动画
- android - 您的应用不符合 Google Play 政策,但确实如此
- rabbitmq - RabbitMQ Http Authentication Backend with SSL
- fortran - Undefined symbols for architecture x86_64 in a NLopt Fortran compilation
- python - Two-point Euclidean distance from csv file
- rust - 所有权转移后的变异变量
- r - 如何加入相似字符的数据集?