我正在尝试将文本文件读入二维字符数组。当我在提取数据后对 ifstream 对象调用 close 时,出现分段错误。
这有效:
problem::problem(obj *o1, obj* o2, char *state_file)
{
ifstream infile;
string line;
infile.open(state_file, ios::in);
getline(infile,line);
infile.close();
}
这不是:
problem::problem(obj *o1, obj* o2, char *state_file)
{
ifstream infile;
string line;
//data is char data[6][7] and is declared in the header
//line is EXACTLY 7 characters lone
infile.open(state_file, ios::in);
for(int i = 5;i >= 0;i--)
{
getline(infile,line);
for(int j = 0;j < 7;j++)
data[i][j] = line[j];
}
cerr << "PROGRAM OK" << endl;
infile.close();
cerr << "The program doesn't get here" << endl;
//Some more constructor code
}
为什么我在调用 infile.close() 时会出现分段错误?
使用相同输入文件的 SSCCE 版本:
#include <string>
#include <fstream>
using namespace std;
class func
{
public:
func(char *);
private:
char data[6][7];
};
func::func(char *state_file)
{
ifstream infile;
string line;
infile.open(state_file, ios::in);
for(int i = 5;i >= 0;i--)
{
getline(infile,line);
for(int j = 0;j < 7;j++)
data[i][j] = line[j];
}
infile.close();
}
int main(int argc, char *argv[])
{
func *obj = new func(argv[1]);
delete obj;
return 0;
}
从主要:
obj *p1 = new obj(&something);
obj *p2 = new obj(&something);
problem *p;
if(argc == 3)
p = new problem(p1, p2, argv[2]); //SEGFAULTS HERE
else
p = new problem(p1, p2);
从带有类声明的标题中:
public:
problem(obj *, obj *);
problem(obj *, obj *, char *);
private:
char data[6][7];