同时读取两个文件(分段错误)c++



这段代码应该在两个.dat文件中读取,格式为:

x y强度例句:

1 1 70
1 2 0.3
1 3 5

它将在一个文件中读取并显示正确的信息,与另一个文件相同,但是当我尝试在两个文件中读取时,我得到一个"分段错误",尽管它正确编译。我不是100%确定为什么,因为每次做一个文件时,它工作,所以我认为它可能不喜欢我在文件中读取的方式。一旦我可以让它工作,我将转移到向量,但我仍在学习它们,并希望首先钉数组。

int main()
{
  std::ifstream file1("p001_1.dat");
  std::ifstream file1_2("p001_2.dat");
    double intensity;
    int i;
    int j;
    double pic1[1392][1040]; //number of pixels
    double pic1_2[1392][1040];
    // reads in file creating an array [x][y] = intensity
    cout<<"Reading in: file1"<<endl;
    if (file1.is_open())
      {
        file1.seekg(0);
        while (!file1.eof())
          {
          file1 >> i >> j >> intensity;
            pic1[i][j] = intensity;
            //cout<<i<<endl
        }
        file1.close();
        //file1.clear();
    }
    else {
      cout << "Error, cannot open file 1"; }
    cout << "Reading in file 2" << endl;    
    if (file1_2.is_open())
      {
        file1_2.seekg(0);
        while (!file1_2.eof())
          {
        file1_2 >> i >> j >> intensity; //
        pic1_2[i][j] = intensity;
          }
        file1_2.close();
        //file1_2.clear();
        //cout<<i<<endl;
      }
    else {
      cout << "Error, cannot open file 1_2"; }
//A LOAD OF CALCULATIONS//

当您运行仅读取单个文件的代码时,您只声明了一个还是两个数组?您的数组都非常大,并且将放置在应用程序堆栈中,堆栈空间不能增长得太大是很正常的。作为一个简单的测试,只需将这些变量移动为全局变量,看看崩溃是否消失。

很可能你得到的是StackOverflow错误

对栈来说太大了:

double pic1[1392][1040]; //number of pixels
double pic1_2[1392][1040];

将它们移出main函数以快速修复它。否则使用动态分配,或者更好的std::vector

最新更新