我是 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;
}
但是当我尝试将读取的数字存储到数据变量中时,出现了段错误。谁能帮我弄清楚出了什么问题?
提前致谢。
最佳答案
我无法解释段错误,但使用 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;
}
}
关于c++ - 我无法弄清楚为什么在使用 ifstream 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35216168/