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

求助:实现字符串匹配判断功能并修正C语言代码错误

Fixing Your C String Matching Program

Let's break down the issues in your code and fix them step by step — there are a few syntax and logical mistakes that are keeping it from running correctly:

Key Issues in Your Original Code

  • Wrong way to compare strings: In C, you can't use = (assignment operator) or even == (equality check for primitives) to compare strings. You need to use the strcmp() function from <string.h> instead. Using = here would actually overwrite your name variable, which is not what you want.
  • Incorrect quote usage: Single quotes (') are only for single characters. Strings like "lucas" need double quotes ("). Your 'lucas' is invalid, and Lucas without quotes is treated as an undefined variable by the compiler, which will throw an error.
  • Broken if-statement syntax: Your if condition has mismatched parentheses and an extra semicolon at the end. That semicolon tells the compiler the if statement ends there, so your printf("do this") block isn't actually tied to the condition at all.

Corrected Code

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

int main(void) {
    char name[10];
    printf("Put your name in: \n");
    // Limit input to 9 characters to avoid buffer overflow (since name has 10 slots total)
    scanf("%9s", name);
    
    // strcmp returns 0 when two strings are identical
    if (strcmp(name, "lucas") == 0 || strcmp(name, "Lucas") == 0) {
        printf("do this");
    } else {
        printf("do that");
    }
    
    return 0; // Properly return an exit status (compliant with C standards)
}

Quick Explanations for the Fixes

  1. strcmp() usage: This function compares two strings character by character. It returns 0 if the strings are exactly the same, a negative number if the first string is "smaller" lexographically, or a positive number if it's "larger". We check for == 0 to confirm a match.
  2. %9s in scanf: Since your name array is sized to 10, we only read 9 characters — this leaves space for the mandatory null terminator (\0) that marks the end of a C string, preventing buffer overflow bugs.
  3. Fixed if-statement: Removed the extra semicolon and matched parentheses correctly, so the condition properly controls which printf runs.
  4. Added return 0: While some compilers let you skip this, it's good practice to return a status code from main to indicate the program ran successfully.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 13:42:30