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

C语言中根据用户输入科目分配结构体section的代码问题求助

问题分析与解决方案

我来帮你排查下这段代码的问题,你遇到的section字段无输出的情况,核心问题出在字符串比较的方式上,还有几个小细节需要调整,咱们一步步来:

主要问题点

  • 字符串不能用==直接比较:C语言里,st[i].sub=="cse"这种写法比较的是两个字符串的内存地址,而不是实际内容。你需要用标准库函数strcmp()来比较字符串内容,记得要引入<string.h>头文件。
  • strcpy(st[i].sec, NULL)的错误:strcpy的第二个参数必须是有效的字符串指针,传入NULL会导致未定义行为,应该改为strcpy(st[i].sec, "")来赋值空字符串。
  • fflush(stdin)的潜在风险:虽然Turbo C支持fflush(stdin)清除输入缓冲区,但这不符合C标准规范,建议用更安全的方式读取并丢弃缓冲区的换行符。
  • 多余的无效指针声明:float *p=&st[i].mrk;这行代码里的i未初始化,而且这个指针从头到尾没有被使用,完全可以删掉。

修正后的完整代码

/*Take value and store in structure member, compare with constant do batch allotment in it.*/
#include <stdio.h>
#include <conio.h>
#include <string.h> // 新增头文件,用于strcmp和strcpy函数

void main() {
    struct student{
        float mrk;
        char sub[10];
        char sec[10];
    } st[2];
    int i;

    clrscr();
    for (i=0; i<2; i++) {
        printf("Enter 12th mrks: ");
        scanf("%f", &st[i].mrk);
        
        // 替代fflush(stdin),安全清除缓冲区的换行符
        while(getchar() != '\n');
        
        printf("Enter subject: ");
        gets(st[i].sub);
    }
    for (i=0; i<2; i++) {
        // 用strcmp比较字符串内容,返回0表示完全匹配
        if (strcmp(st[i].sub, "cse") == 0) {
            strcpy(st[i].sec, "A");
        } else if (strcmp(st[i].sub, "me") == 0) {
            strcpy(st[i].sec, "B");
        } else {
            strcpy(st[i].sec, ""); // 赋值合法的空字符串
        }
    }
    printf("\n numbers \t sub \tsec \n");
    printf("-------------------------------------\n");
    for (i=0; i<2; i++) {
        printf("%f\t%s\t%s\n", st[i].mrk, st[i].sub, st[i].sec);
    }
    getch();
}

修正说明

  1. 新增<string.h>头文件:为strcmp(字符串比较)和strcpy(字符串复制)提供函数支持;
  2. 替换字符串比较逻辑:用strcmp(st[i].sub, "cse") == 0替代st[i].sub=="cse",确保比较的是字符串实际内容;
  3. 优化输入缓冲区处理:用while(getchar() != '\n');替代fflush(stdin),符合C标准且更安全;
  4. 修正空字符串赋值:把NULL改为"",避免非法指针导致的未定义行为;
  5. 移除无效代码:删掉了未使用的指针声明,让代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:05:26