我正在尝试将文本文件读入二维字符数组。当我在提取数据后在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;
}
来自main:
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];
答案 0 :(得分:1)
您确定您的文件始终包含至少六行吗?
在ifstream上“迭代”的常用方法是:
ifstream is("test.txt");
string line;
while(getline(is, line))
{
cout<<line<<endl;
}
答案 1 :(得分:0)
我明白了。该问题与在构建过程中如何链接目标文件有关。删除所有.o文件并从头开始重建解决了这个问题。谢谢大家的意见。我为从一开始就不干净的构建而浪费你的时间而道歉。