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

使用MS Visual Studio 2022时程序输出正常但触发abort()调用错误

问题分析与修复方案

错误原因

  1. 字符串越界访问:你的循环条件用了i <= strX.length(),但C++字符串的索引范围是0到length()-1。当i等于字符串长度时,调用at(i)会触发std::out_of_range异常,进而触发abort()。
  2. 未检查文件状态:代码里没有判断inFile.open()是否成功,如果strings.txt不存在、路径错误或无读取权限,后续的getline操作会导致字符串为空,同样会引发越界问题。
  3. 短字符串越界风险:当三个字符串长度不一致时,循环到超过短字符串长度的索引时,短字符串的at(i)依然会触发越界异常。

修复后的代码

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    string str1, str2, str3;
    ifstream inFile;

    // 检查文件是否成功打开
    inFile.open("strings.txt");
    if (!inFile.is_open()) {
        cerr << "无法打开文件 strings.txt" << endl;
        system("pause");
        return 1;
    }

    getline(inFile, str1);
    getline(inFile, str2);
    getline(inFile, str3);
    inFile.close(); // 读取完成后关闭文件

    // 获取三个字符串的最大长度
    size_t maxLen = max(max(str1.length(), str2.length()), str3.length());

    // 循环遍历到最大长度-1,避免越界
    for (size_t i = 0; i < maxLen; ++i) {
        // 短字符串用空格填充,避免越界访问
        char c1 = (i < str1.length()) ? str1.at(i) : ' ';
        char c2 = (i < str2.length()) ? str2.at(i) : ' ';
        char c3 = (i < str3.length()) ? str3.at(i) : ' ';
        cout << c1 << " " << c2 << " " << c3 << endl;
    }

    system("pause");
    return 0;
}

关键修改点

  • 增加文件打开状态检查,避免文件读取失败引发后续错误。
  • 循环条件改为i < maxLen,确保索引不会超出任何字符串的有效范围。
  • 对短字符串的索引位置用空格填充,既保证输出格式整齐,又避免越界访问。
  • 读取完成后关闭文件,养成良好的资源管理习惯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:30:52