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

C语言座位预订程序:指针整数比较错误及跨函数输入传递问题

C语言座位预订程序问题解答

问题1:字符串比较导致的编译错误

错误原因

  • p.name 是结构体中的char[50]类型(字符串),而你声明的passengername是char类型(单个字符),二者类型不匹配;
  • C语言中字符串不能直接用==比较,==比较的是字符串的首地址,而非内容。

解决步骤

  1. 修改update函数中passengername的类型为字符串数组:
    char passengername[50];
    
  2. 读取输入时使用%s格式符:
    scanf(" %s", passengername);
    
  3. 使用strcmp函数比较字符串内容,当返回值为0时表示两字符串相等:
    if(strcmp(p.name, passengername) == 0)
    
    注:strcmp需要包含头文件<string.h>,你的代码已包含该头文件,无需额外添加。

问题2:跨函数传递用户输入的座位信息

错误原因

chooseseat函数中声明的passenger p是局部变量,和reserve函数中的p是完全独立的两个变量,修改局部变量不会影响reserve中的变量,因此输出为初始值0。

解决步骤

使用指针传递,让chooseseat直接修改reserve函数中p的内容:

  1. 修改chooseseat的函数声明和定义,接收passenger类型的指针:
    void chooseseat(passenger *p);
    
  2. 在reserve函数中调用时传入p的地址:
    chooseseat(&p);
    
  3. 修改chooseseat函数内部的代码,用->访问指针指向的结构体成员:
    void chooseseat(passenger *p){
        // 补充未声明的变量:座位状态数组和用户选择变量
        char seat[ROWS][COLS] = {0}; // 可改为全局变量方便多函数访问
        char answer;
        
        printf("\nEnter your seat number: (EX: 1A)");
        scanf(" %d%c", &(p->seatrow), &(p->seatcol));
    
        if (p->seatrow > 0 && p->seatrow < ROWS &&
            p->seatcol >= 'A' && p->seatcol <= 'A' + COLS){
    
            if (seat[p->seatrow - 1][p->seatcol - 'A'] != 'X'){
                seat[p->seatrow - 1][p->seatcol - 'A'] = 'X';
                printf("Congratulations. Your seat number is %d%c\n", p->seatrow, p->seatcol);
            } else {
                printf("Seat is already taken. Choose another seat? (Y/N)\n");
                scanf(" %c", &answer);
                if (answer != 'Y'){
                    printf("Your data will be not saved and will be returned to main menu.\n");
                }
            }
        } else {
            printf("Invalid seat row/col,\n");
        }
    }
    

额外代码问题提示

  • update函数中使用的p未声明,需在函数内添加passenger p;;
  • update函数中的displayseat函数未定义,需补充实现或删除该调用;
  • reserve函数中使用的write函数应为fwrite,正确写法是fwrite(&p, PASSENGERSIZE, 1, fp1);;
  • 结构体中的city、age、id、seatnum字段未使用,可根据需求补充逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 04:36:17