c++ - 尝试从 istream 存储 token 时出现段错误

标签 c++ input io fstream

我的代码在读取文件时崩溃(见本文末尾)。我在 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/

相关文章:

c++ - 在 Qt 中单击 QTableView 中某一行的特定单元格时打开一个新窗口

c++ - "inline"功能的用处

c++ - CString.Replace 替换多个字符

html - 如何格式化 Opera 浏览器的输入占位符文本?

sockets - 向套接字发送(或接收)数据时出错(Haskell)

Java 设计问题

c++ - 有没有办法在旧版 C/C++ 编译器中使用 C++ 11 线程对象

ruby-on-rails - 如何在 Rails 表单中添加下拉 <select> 字段?

java - 使用 Java 检查文本文件中是否已存在输入

python - python "with"命令可以用于选择性地写入文件