You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C语言中比较用户输入字符串与指针存储的字符串?

嘿,我看你正在开发一个仇恨犯罪举报系统,需要实现用户输入内容和指针存储单词的比较功能。我帮你梳理下现有代码,再给出可行的实现方案:

现有代码片段

首先先把你提供的未完成代码整理出来:

int c_s(char*, char*);
int main() {
    printf("Hate crime reporting system\n\n\n");
    printf("If the crime you are reporting is an emergency,\nplease call 999, do not proceed any further with this form\n\n\n\nPlease press enter to confirm you have read the above and continue\n");
    char enter = 0;
    while (enter != '\r' && enter != '\n') {
        enter = getchar();
    }
    int a;
    long long in... // 这里是未完成的输入处理部分
}
实现字符串比较功能的方案

你声明的c_s函数看起来是用来比较两个字符串的,下面给你两种实现方式,以及后续的输入处理逻辑:

1. 自定义字符串比较函数

如果你不想用标准库的strcmp,可以自己实现这个c_s函数,逻辑和标准库类似:

// 自定义字符串比较函数
// 返回值说明:0=两字符串相等,正数=前者大于后者,负数=前者小于后者
int c_s(char *str1, char *str2) {
    // 逐个字符比较,直到遇到不同字符或字符串结束
    while (*str1 != '\0' && *str2 != '\0' && *str1 == *str2) {
        str1++;
        str2++;
    }
    // 返回最后一个字符的ASCII差值
    return *str1 - *str2;
}

2. 完善用户输入与比较逻辑

接下来你需要读取用户输入,然后和目标单词(指针存储的内容)进行比较,这里补充完整的main函数逻辑:

#include <stdio.h>
#include <string.h> // 用到strcspn函数去除换行符

int c_s(char*, char*);

int main() {
    printf("Hate crime reporting system\n\n\n");
    printf("If the crime you are reporting is an emergency,\nplease call 999, do not proceed any further with this form\n\n\n\nPlease press enter to confirm you have read the above and continue\n");
    char enter = 0;
    while (enter != '\r' && enter != '\n') {
        enter = getchar();
    }

    // 假设指针存储的目标单词是这个,你可以根据需求修改
    char *target_word = "harassment";
    char user_input[100]; // 定义缓冲区存储用户输入,大小可按需调整

    // 提示用户输入
    printf("\nPlease enter the content you want to compare: ");
    // 用fgets读取输入,避免缓冲区溢出
    fgets(user_input, sizeof(user_input), stdin);
    // 去除fgets自动读取的换行符
    user_input[strcspn(user_input, "\n")] = '\0';

    // 调用自定义的c_s函数比较
    int compare_result = c_s(user_input, target_word);
    if (compare_result == 0) {
        printf("\nYour input matches the target word!\n");
    } else if (compare_result > 0) {
        printf("\nYour input is lexicographically larger than the target word.\n");
    } else {
        printf("\nYour input is lexicographically smaller than the target word.\n");
    }

    return 0;
}

// 把刚才的c_s函数实现放在这里
int c_s(char *str1, char *str2) {
    while (*str1 != '\0' && *str2 != '\0' && *str1 == *str2) {
        str1++;
        str2++;
    }
    return *str1 - *str2;
}

3. 关键注意点

  • 输入安全:用fgets代替scanf("%s")可以避免用户输入过长导致的缓冲区溢出问题,同时记得用strcspn去除换行符,不然输入内容会带个\n影响比较。
  • 空指针检查:如果你的目标单词指针可能为空,记得在c_s函数里先判断str1和str2是否为NULL,避免程序崩溃。
  • 简化比较逻辑:如果你只需要判断是否相等,不需要排序比较,可以把c_s函数简化为返回1(相等)或0(不等),逻辑更直观。

内容的提问来源于stack exchange,提问作者Joepoint

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:19:10