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

C++学生信息查询LAB try/catch异常处理及编译警告问题

C++ LAB作业故障排查与修复

编译警告信息

main.cpp: In function ‘std::string FindID(std::string, std::ifstream&)’:
main.cpp:24:1: warning: control reaches end of non-void function [-Wreturn-type]
   24 | }
      | ^
main.cpp: In function ‘std::string FindName(std::string, std::ifstream&)’:
main.cpp:49:1: warning: control reaches end of non-void function [-Wreturn-type]
   49 | }
      | ^

作业核心要求

  • 实现两个查询函数:FindID()按姓名查ID,FindName()按ID查姓名,未匹配到对应记录时必须抛出std::runtime_error类型异常,异常信息符合指定格式
  • main函数中使用try/catch捕获上述两个函数抛出的异常,直接输出异常信息
  • 输入文件每行存储空格分隔的学生姓名和ID

故障现象

  • 10个测试点仅通过5个
  • 按ID查询不存在记录时无输出
  • 函数抛出异常测试返回错误码-6

根因分析

  1. 函数逻辑路径覆盖不全:两个查询函数仅在匹配到记录时有return返回,未匹配到记录的分支没有写抛出异常的代码,导致程序运行到函数末尾直接退出,既无返回值也无异常抛出,属于未定义行为,直接触发编译警告和运行时异常
  2. 文件流状态未重置:多次调用查询函数时,文件流读指针已经指向文件末尾,且可能存在流错误标记,导致遍历直接跳过,也会触发无返回无抛异常的问题

修复方案

1. 补全查询函数的异常抛出逻辑+流状态重置

FindID函数实现示例

#include <stdexcept>
#include <string>
#include <fstream>

std::string FindID(std::string targetName, std::ifstream& file) {
    // 每次查询前重置流状态和读指针到文件开头
    file.clear();
    file.seekg(0, std::ios::beg);
    std::string name, id;
    while (file >> name >> id) {
        if (name == targetName) {
            return id;
        }
    }
    // 未匹配到必须抛出异常,覆盖所有控制流路径
    throw std::runtime_error("Student ID not found for " + targetName);
}

FindName函数实现示例

std::string FindName(std::string targetId, std::ifstream& file) {
    file.clear();
    file.seekg(0, std::ios::beg);
    std::string name, id;
    while (file >> name >> id) {
        if (id == targetId) {
            return name;
        }
    }
    throw std::runtime_error("Student name not found for " + targetId);
}

2. 补全main函数的try/catch捕获逻辑

#include <iostream>
int main() {
    std::string filename, keyword;
    int option;
    std::cin >> filename >> option >> keyword;
    std::ifstream inputFile(filename);
    try {
        if (option == 0) {
            std::cout << FindID(keyword, inputFile) << std::endl;
        } else if (option == 1) {
            std::cout << FindName(keyword, inputFile) << std::endl;
        }
    } catch (const std::runtime_error& e) {
        std::cout << e.what() << std::endl;
    }
    inputFile.close();
    return 0;
}

验证说明

修复后编译警告会完全消失,未匹配到记录时会正常抛出异常并被捕获输出,所有测试点可正常通过。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:36:02