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

C语言投票程序无法保存候选人姓名,投票提示无效及结构体赋值报错问题

解决C语言投票项目的候选人存储与投票匹配问题

问题1:用char *name时投票提示无效

投票持续提示无效,核心原因是你用了==比较字符串,而非strcmp()。C语言里==对比的是字符串的内存地址,不是实际内容——命令行传入的候选人和投票输入的字符串地址不同,自然永远匹配失败。

修复方案:

  • 结构体保留char *name即可,命令行参数argv的字符串在程序运行期间有效,直接存储指针完全可行。
  • 在vote()函数里用strcmp()对比字符串内容,返回值为0时代表匹配成功。

示例代码片段:

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

typedef struct {
    char *name;
    int votes;
} Candidate;

Candidate candidates[10];
int candidate_count;

bool vote(char name[]) {
    for (int i = 0; i < candidate_count; i++) {
        // 用strcmp比较字符串内容,不能用==
        if (strcmp(candidates[i].name, name) == 0) {
            candidates[i].votes++;
            return true;
        }
    }
    printf("Invalid vote\n");
    return false;
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: ./out [候选人姓名]\n");
        return 1;
    }
    candidate_count = argc - 1;
    for (int i = 0; i < candidate_count; i++) {
        candidates[i].name = argv[i+1]; // 直接指向命令行参数的字符串
        candidates[i].votes = 0;
    }
    // 后续选民数量输入、投票逻辑...
    return 0;
}

问题2:改成char name[10]时出现数组赋值错误

C语言中数组不能直接用=赋值,必须用字符串拷贝函数完成内容复制。

修复方案:

  • 结构体定义为char name[10];(注意长度要足够容纳最长候选人姓名+结束符)
  • 初始化时用strncpy()(比strcpy更安全,避免缓冲区溢出)把命令行参数的字符串拷贝到数组中。

示例代码片段:

typedef struct {
    char name[10];
    int votes;
} Candidate;

int main(int argc, char *argv[]) {
    // ... 参数检查逻辑
    for (int i = 0; i < candidate_count; i++) {
        // 拷贝字符串,第三个参数设为数组长度-1,预留结束符位置
        strncpy(candidates[i].name, argv[i+1], sizeof(candidates[i].name)-1);
        // 手动添加结束符,防止源字符串过长时strncpy不自动补全
        candidates[i].name[sizeof(candidates[i].name)-1] = '\0';
        candidates[i].votes = 0;
    }
    // ...
}

额外注意事项

  • 如果候选人姓名可能超过10个字符,需调整数组长度,或者用malloc动态分配内存配合strcpy使用。
  • 若允许投票输入带首尾空格,需在对比前先处理掉多余空格,避免匹配失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 06:03:21