c - 如何检查变量中是否包含某个字符串?在if条件下如何做到这一点?
问题描述
到目前为止,我有以下内容:
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <string.h>
int main (void)
{
printf("Loading BES Command Prompt...\n");
sleep(5);
printf("> ");
char *input;
scanf("%s", input);
printf("\n");
if (input == "exit")
{
printf("Terminating BEScmd.c...\n");
sleep(2);
return 100;
}
}
但是我需要帮助,因为它不会使用printf("Terminating BEScmd.c...\n");
并且编译器说它以退出代码“0”而不是“100”中止,这是我希望它停止的。
你能帮帮我吗?
解决方案
您可以使用 strcmp(a,b); 来自 string.h 库。
像这样:
string a = "words";
string b = "words";
if (strcmp(a, b) == 0)
{
printf("a and b match");
// strcmp returns 0 if both strings match
}
else
{
printf("a and b don't match");
// strcmp returns anything else if the strings dont match
}
推荐阅读
- selenium - 如何获取输入中的值
- c# - 为什么 DateTime.UtcNow.Subtract 有时会给我一个很大的数字?
- python - pip卸载的顺序重要吗?
- r - 如何避免模块代码过早运行?
- botframework - 使用 BotFramework 的 WebChat 自动完成
- hyper-v - Hyper-V 在睡眠后断开增强会话
- asp.net-mvc - Sitefinity 如何让自定义用户控件仅在预览/实时模式下显示
- java - Apache Lucene for Java:IndexWriter.addDocument 与 addDocuments(速度)
- stripe-payments - 连接帐户的 Stripe Checkout 给出“Invalid payment_page id”错误
- python - 从 python 字典自动生成 BigQuery 架构