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

C++读取txt文件前两列存入数组后打印数值异常问题求助

问题根因

你代码的核心错误是数组索引变量j的定义位置不对:

  • 你把int j = 0;写在了while循环内部,每次循环执行时都会把j重置为0,所以所有读取到的数值都会被反复写入col1[0]、col2[0]两个位置
  • 数组剩下的99个元素全程没有被赋值,属于未初始化的栈内存,打印出来自然是随机的异常数值
修复方案

把j的定义移到while循环外部即可,优化后的完整代码如下:

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

using namespace std;

void func(){
    // 初始化数组,避免文件行数不足100时输出垃圾值
    int col1[100] = {0};
    int col2[100] = {0};
    int temp = 1;
    // 直接用构造函数打开文件,写法更简洁
    ifstream in("file.txt");
    if (in.fail()){
        cout << "failed to open" << endl;
        exit(1);
    }
    string line;
    int temp1, temp2;
    // 索引变量移到循环外初始化
    int j = 0;

    while(getline(in, line) && temp <= 100) {
        istringstream iss(line);
        iss >> temp1 >> temp2;
        cout << temp1 << ' ' << temp2 <<'\n';
        col1[j] = temp1;
        col2[j] = temp2;
        j++;
        temp++;
    }
    cout<<"arrays"<<'\n';
    // 如果文件不足100行,只打印实际读取到的行数,避免输出未初始化的值
    for (int i=0; i < j; i++){
        cout << col1[i] << ' ' << col2[i] <<'\n';
    }
}
额外优化建议
  • 如果不确定文件行数,建议用std::vector<int>代替固定大小的数组,不需要预先设定容量,自动扩容更安全
  • 可以加读取校验,判断iss >> temp1 >> temp2是否执行成功,避免行格式不符合预期时写入错误值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:54:02