首页 > 解决方案 > 如何检查变量中是否包含某个字符串?在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”中止,这是我希望它停止的。

你能帮帮我吗?

标签: c

解决方案


您可以使用 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
}

推荐阅读