读取输入时丢失末尾元素:问题排查与修复方案咨询
问题描述
需要读取的输入格式如下:
0 50 50 100 30 40 30 50 10 100 20 30 40 50 60 70 80 90
当前实现无法读取-1之前的最后一个数字,导致第一个进程丢失“100”,第二个进程丢失“90”。使用Process结构体接收输入,询问问题原因及修复方法。
附上当前代码:
typedef struct { int arrival; int numofProcesses; int *cpu_times; int *io_times; } Process; void readInput(Process *queue, int *rear) { while (true) { int arrival_time; int cpu; int io; if (scanf("%d", &arrival_time) == EOF) break; int *cpu_times = (int *)malloc(SIZE * sizeof(int)); int *io_times = (int *)malloc(SIZE * sizeof(int)); int num_of_bursts = 0; while (true) { scanf("%d", &cpu_time); scanf("%d", &io_time); /* end the process when encountering -1*/ if (cpu_time == -1 || io_time == -1) break; /* add the input to the data in struct */ cpu_times[num_of_bursts] = cpu_burst; io_times[num_of_bursts] = io_time; num_of_bursts++; } if (num_of_bursts > 0) { Process nP = {arrival_time, num_of_bursts, cpu_times, io_times}; arrival_queue[++(*rear)] = nP; } else { free(cpu_times); free(io_times); } } }
问题原因
- 读取逻辑顺序错误:代码先强制读取一组
cpu_time和io_time再判断结束标志,但进程的最后一个CPU burst后没有对应的IO时间,一旦遇到-1或输入结束,刚读取的有效CPU时间会直接被丢弃。 - 变量名不一致:声明的变量是
cpu,但使用时写成cpu_time、cpu_burst,属于未定义变量,编译会报错。 - EOF处理缺失:当输入到末尾无更多数据时,
scanf返回EOF,此时已读取的最后一个CPU时间未存入数组就退出循环。
修复方案
调整读取逻辑:先读CPU时间,判断是否为结束标志;若不是,再读IO时间,同时处理IO时间为-1或输入结束的情况(此时仅保存CPU时间)。同时修正变量名错误。
修复后的代码:
#include <stdio.h> #include <stdlib.h> #define SIZE 100 // 假设SIZE已提前定义 typedef struct { int arrival; int num_of_bursts; // 修正命名,更贴合实际含义 int *cpu_times; int *io_times; } Process; void readInput(Process *arrival_queue, int *rear) { while (true) { int arrival_time; if (scanf("%d", &arrival_time) == EOF) break; int *cpu_times = (int *)malloc(SIZE * sizeof(int)); int *io_times = (int *)malloc(SIZE * sizeof(int)); int num_of_bursts = 0; while (true) { int cpu_time; // 先读取CPU时间,判断是否结束 if (scanf("%d", &cpu_time) == EOF || cpu_time == -1) { break; } cpu_times[num_of_bursts] = cpu_time; int io_time; // 读取IO时间,判断是否为最后一个burst if (scanf("%d", &io_time) == EOF || io_time == -1) { num_of_bursts++; break; } io_times[num_of_bursts] = io_time; num_of_bursts++; } if (num_of_bursts > 0) { Process nP = {arrival_time, num_of_bursts, cpu_times, io_times}; arrival_queue[++(*rear)] = nP; } else { free(cpu_times); free(io_times); } } }
修复说明
- 调整读取顺序:先处理CPU时间,再按需处理IO时间,确保最后一个CPU burst能被正确保存。
- 修正变量名:统一代码中不一致的变量名,消除编译错误。
- 完善EOF处理:输入到末尾时,不会丢失最后一个有效CPU时间。
- 优化结构体命名:将
numofProcesses改为num_of_bursts,更准确反映成员含义。
内容的提问来源于stack exchange,提问作者travxx
相关产品推荐
相关产品推荐

