我是C ++的新手。我正在尝试打开一个文件并将其传递给另一个方法,以便我可以从ifstream读取数据。这是打开文件的方法。
int main() {
// part 1
ifstream infile1("data31.txt");
if (!infile1) {
cout << "File could not be opened." << endl;
return 1;
}
//for each graph, find the shortest path from every node to all other nodes
for (;;) {
int data = 0;
GraphM G;
G.buildGraph(infile1);
if (infile1.eof())
break;
}
return 0;
}'
然后我在另一个名为GraphM的类中有另一个方法,我已经用这种方式实现了它:
void GraphM::buildGraph(ifstream& infile1) {
int data = 0;
infile1 >> data;
cout << "data = " << data << endl;
}
但是当我尝试将读取的数字存储到数据变量中时,我遇到了分段错误。任何人都可以帮我弄清楚出了什么问题吗?
提前致谢。
答案 0 :(得分:1)
我无法解释分段错误,但使用infile.eof()
来破解不是一个好策略。有关详细信息,请参阅Why is iostream::eof inside a loop condition considered wrong?。
我建议使用:
int main() {
ifstream infile1("data31.txt");
if (!infile1) {
cout << "File could not be opened." << endl;
return 1;
}
// Continue reading as long as the stream is valid.
for (; infile1 ;) {
GraphM G;
G.buildGraph(infile1);
}
return 0;
}
void GraphM::buildGraph(ifstream& infile1) {
int data = 0;
if ( infile1 >> data )
{
// Data extraction was successful.
cout << "data = " << data << endl;
}
}