c++ - cmd 窗口停止工作,文本文件被 fstream 读取错误

标签 c++ arrays fstream

在函数 Read() 中,当我输出数组 klas[] 和 nauj[] 时,一切似乎都可以正常读取,但回到主函数后,它们被破坏并且似乎被其他文本文件填充。你知道这里有什么问题吗?

#include <iostream>
#include <fstream>

using namespace std;

const char klase[] = "klase.txt";
const char naujokai[] = "lele.txt";

void Read(int klas[], int nauj[], int &nk, int &nj);

int main()
{
    int klas[] = {};
    int nauj[] = {};
    int nk;
    int nj;
    Read(klas, nauj, nk, nj);

    for(int i = 0; i < nk; i++){
        cout << klas[i] << endl;
    }for(int i = 0; i < nj; i++){
        cout << nauj[i] << endl;
    }



    return 0;
}

void Read(int klas[], int nauj[], int &nk, int &nj)
{
    ifstream fklase(klase);
    fklase >> nk;
    for(int i = 0;i < nk;i++){
        fklase >> klas[i];
        cout << klas[i] << endl << endl;
    }
    fklase.close();
    ifstream fnaujokai(naujokai);
    fnaujokai >> nj;
    for(int i = 0; i < nj; i++){
        fnaujokai >> nauj[i];
        cout << nauj[i] << endl << endl;
    }
    fnaujokai.close();

}

最佳答案

诸如 int klas[] = {}; 之类的零大小数组不是标准的,并且像在 fklase >> klas[i]; 中那样写入它们;是未定义的行为,因为它们没有空间存储任何东西。另请注意,当您使用 int klas[] 作为函数参数时,它实际上等同于 int * klas

关于c++ - cmd 窗口停止工作,文本文件被 fstream 读取错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46390735/

相关文章:

C++:从文件中读取并显示单个项目

c++ - 不确定如何解决 'std::out_of_range' 错误

c++ - 有没有办法在C++中动态清除文本文件的内容?

c++ - OpenCV col-wise 标准偏差结果与 MATLAB

c++ - 将类作为参数传递c++

python - Numpy:沿轴应用具有不同索引的输入数组

c - 尝试打印二维数组中的值

c++ - 将从公共(public)接口(interface)派生的类的对象存储在公共(public)容器中的最安全方法是什么?

c++ - 是否可以使用 operator new 和 initialiser 语法初始化非 POD 数组?

c++ - 文件中的字符不正确