我的代码在读取文件时崩溃(见本文末尾)。我在 main 中声明一个 ifstream 对象,将其传递给 buildGraph 函数(将 ifstream& 作为参数),并尝试将第一个标记传递到字符串 temp 中。
main的相关代码:
#include <fstream>
int main() {
ifstream infile1("data31.txt");
if (!infile1) {
cout << "File could not be opened." << endl;
return 1;
}
GraphM G;
G.buildGraph(infile1);
}
来自graphm.cpp的相关代码:
#include <fstream>
#include <string>
void GraphM::buildGraph(ifstream& input)
{
string temp;
input >> temp;
}
还有一个头文件 graphm.h 也包含 fstream。我和几个在我所在的大学工作的导师谈过,他们根本帮不上忙,因为他们和我一样困惑。函数 getline() 也会抛出一个段错误,所以它不会起作用。我在这里做错了什么?
此外,我正在阅读的 .txt:
5
Aurora and 85th
Green Lake Starbucks
Woodland Park Zoo
Troll under bridge
PCC
1 2 50
1 3 20
1 5 30
2 4 10
3 2 20
3 4 40
5 2 20
5 4 25
0 0 0
3
aaa
bbb
ccc
1 2 10
1 3 5
2 3 20
3 2 4
0 0 0
最佳答案
(包含评论作为允许代码格式化的答案)
构造一个SSCCE我将所有代码包含在一个文件中,如下所示:
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
class GraphM {
public:
void buildGraph(ifstream& input);
};
void GraphM::buildGraph(ifstream& input)
{
string temp;
input >> temp;
cout << temp;
}
int main() {
ifstream infile1("data31.txt");
if (!infile1) {
cout << "File could not be opened." << endl;
return 1;
}
GraphM G;
G.buildGraph(infile1);
}
然后我编译并运行了代码并获得了预期的输出 5
。
然后我将代码分成问题中描述的三个文件,编译并运行它们,再次得到相同的结果,5
。我在 Windows 7 的 cygwin 中使用 GNU C++ 4.7.3。
你能告诉我们更多关于你使用的编译器和你系统的其他细节吗?
关于c++ - 尝试从 istream 存储 token 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23283337/