【发布时间】:2013-03-14 11:33:31
【问题描述】:
此代码应读入两个 .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//
【问题讨论】:
-
你应该在调试器中运行它,因为它会告诉你哪一行导致了段错误。
-
`尽管编译正确,但我得到一个“分段错误”`-我敢打赌,您从未收到未正确编译的代码的分段错误。跨度>
-
您检查过
i和j之间的值吗?你从哪里得到段错误?你调试过程序吗? -
一次运行一个时,它会正确读取和存储数组,我可以将它们显示在我的屏幕上。两者都使用时,它甚至不会让我显示代码的任何部分。它只是立即出错。
-
@fiz,当您不读取第二个文件时,这是正确的,编译器优化了第二个数组和堆栈因此不会溢出