You need to enable JavaScript to run this app. C语言汽车开票系统一次性输入下newInvoice函数scanf异常求解
优惠活动
大模型
产品
解决方案
定价
更多

C语言汽车开票系统一次性输入下newInvoice函数scanf异常求解

输入异常根源

你当前的输入异常由三个核心问题导致:

  • scanf格式符混用导致输入缓冲区残留:用%d、 %c读取数值或字符后,用户输入的换行符会留在缓冲区,下一次用%[^\n]读取字符串时会直接匹配残留换行,返回空值,出现输入跳过、内容错位的问题。
  • 无长度限制的字符串读取:%[^\n]未指定最大读取长度,输入超过结构体数组大小时会发生缓冲区溢出,破坏程序内存。
  • 未实现要求的一次性采集逻辑:当前代码是分多次提示、分多次输入,和你需要的一次性采集需求不符。
修复方案

直接改用单次行读取+字段拆分的逻辑,一次性采集所有输入,同时用安全的fgets替代scanf读取字符串,从根源上避免缓冲区残留和溢出问题。

核心改动说明

  • 新增统一的输入清空函数,每次读取输入后清理缓冲区残留。
  • 提示用户按固定格式一次性输入所有字段,用|做分隔符,避免多次输入的逻辑。
  • 所有字符串读取用strncpy实现,自动限制最大长度,杜绝溢出。
  • 数值类字段自动从拆分后的字符串转换,无需额外单独输入。

修复后完整可运行代码

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <memory.h>
#include <ctype.h>
#include <time.h>

struct customer
{
    char name[45];
    char invoice[4];
    char service[2];
    char carNo[16];
    char fee[5]; // 扩大字段避免费用长度溢出
    bool urgent;
    time_t date;
};

/*********************************************************************************************/
void toFile(char*);
void displayMenu(void);
void newInvoice(int invoiceNo);
// 清空输入缓冲区残留
void clearInputBuffer()
{
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}
/*********************************************************************************************/
int main()
{
    char toContinue;
    int invoiceNo = 1;
    do
    {
        newInvoice(invoiceNo);
        invoiceNo += 1;
        printf("是否继续生成下一个订单?(Y/N): ");
        scanf(" %c", &toContinue);
        clearInputBuffer();
    }
    while (toContinue != 'N' && toContinue != 'n');
    return 0;
}
/*********************************************************************************************/
void newInvoice(int invoiceNo)
{
    struct customer *newCus = (struct customer*) malloc(sizeof(struct customer));
    if (newCus == NULL) {
        printf("内存分配失败\n");
        exit(EXIT_FAILURE);
    }

    displayMenu();
    printf("\n按任意键开始采集客户信息...\n");
    getchar();
    clearInputBuffer();

    sprintf(newCus->invoice, "%d", invoiceNo);

    // 一次性采集所有输入的提示
    printf("请按以下格式一次性输入所有信息(用|分隔,不要加空格):\n");
    printf("客户姓名|车牌号|服务编号|是否加急(Y/N)|费用\n");
    printf("示例:张三|粤B12345|3|Y|90\n> ");

    // 单次读取整行输入
    char inputBuf[256] = {0};
    if (fgets(inputBuf, sizeof(inputBuf), stdin) == NULL) {
        printf("输入读取失败\n");
        free(newCus);
        exit(EXIT_FAILURE);
    }
    // 去掉fgets读取的末尾换行符
    inputBuf[strcspn(inputBuf, "\n")] = '\0';

    // 拆分字段
    char *token = strtok(inputBuf, "|");
    int fieldIdx = 0;
    while (token != NULL && fieldIdx < 5) {
        switch(fieldIdx) {
            case 0: // 客户姓名
                strncpy(newCus->name, token, sizeof(newCus->name)-1);
                newCus->name[sizeof(newCus->name)-1] = '\0';
                break;
            case 1: // 车牌号
                strncpy(newCus->carNo, token, sizeof(newCus->carNo)-1);
                newCus->carNo[sizeof(newCus->carNo)-1] = '\0';
                break;
            case 2: // 服务编号
                strncpy(newCus->service, token, sizeof(newCus->service)-1);
                newCus->service[sizeof(newCus->service)-1] = '\0';
                break;
            case 3: // 是否加急
                newCus->urgent = (tolower(token[0]) == 'y');
                break;
            case 4: // 费用
                strncpy(newCus->fee, token, sizeof(newCus->fee)-1);
                newCus->fee[sizeof(newCus->fee)-1] = '\0';
                break;
        }
        token = strtok(NULL, "|");
        fieldIdx++;
    }

    // 校验是否所有字段都输入完整
    if (fieldIdx < 5) {
        printf("输入格式错误,请按要求用|分隔5个字段\n");
        free(newCus);
        exit(EXIT_FAILURE);
    }

    time(&newCus->date); // 获取系统时间

    // 写入文件
    toFile("Invoice:\t");
    toFile(newCus->invoice);
    toFile("  customer: ");
    toFile(newCus->name);
    toFile("  vehicle: ");
    toFile(newCus->carNo);
    toFile("  service: ");
    toFile(newCus->service);
    toFile("  type: ");
    if(newCus->urgent)
        toFile("urgent");
    else
        toFile("normal");
    toFile("  fee: ");
    toFile(newCus->fee);
    toFile("  date: ");
    toFile(ctime(&newCus->date));

    // 控制台输出发票
    printf("\n=== 生成发票 ===\n");
    printf("客户姓名:%s\n车牌号:%s\n服务编号:%s\n类型:%s\n费用:%s\n日期:%s\n",
        newCus->name, newCus->carNo, newCus->service,
        newCus->urgent?"urgent":"normal", newCus->fee, ctime(&newCus->date));

    free(newCus);
}
/*********************************************************************************************/
void displayMenu()
{
    printf("\n=== 汽车服务菜单 ===\n");
    printf("编号  服务类型                     耗时(分钟)  普通费用  加急费用\n");
    printf("1     补胎(单个)                   10          5        6\n");
    printf("2     换胎(单个)                   15          150      160\n");
    printf("3     矿物油更换                   20          80       90\n");
    printf("4     合成油更换                   10          130      140\n");
    printf("5     更换电池                     5           200      210\n");
    printf("6     更换前大灯灯泡(单个)         5           6        8\n");
    printf("7     更换尾灯灯泡(单个)           5           6        8\n");
    printf("8     洗车                         10          10       12\n");
}
/*********************************************************************************************/
void toFile(char* Str2Write)
{
    FILE *file2write = fopen("record.txt", "a");
    if(file2write == NULL) {
        printf("文件写入失败\n");
        exit(EXIT_FAILURE);
    }
    fprintf(file2write, "%s", Str2Write);
    fclose(file2write);
}
改动说明
  • 把原来的分5次提示输入改成一次性提示格式、用户单次输入整行,完全符合你要求的一次性采集逻辑。
  • 所有字符串读取都用strncpy限制最大长度,不会出现缓冲区溢出。
  • 新增clearInputBuffer函数,每次读取完输入后清理残留的换行符,彻底解决之前的输入跳过、内容错位问题。
  • 修正了原来toFile写入的文件名错误(原注释要求写入record.txt,旧代码误写为file.txt)。
  • 扩大了fee数组的长度,避免输入3位以上费用时溢出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.15 19:54:04