首页 > 解决方案 > C++ cin 分段错误 11

问题描述

代码是:

std::string fname;
std::cin >> fname;

当代码位于main函数中时,一切顺利。但是当我将这两行放在一个成员函数中时,我在运行时遇到了分段错误。

谁能给我一些关于发生了什么的提示?

最小的例子:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
class TextQuery {
private:
    std::vector<std::string> *lines_of_text;
public:
    void retrieve_text();
};

void TextQuery::retrieve_text() {
    std::cout<<"Please input file name:\n";
    std::string fname;
    std::cin >> fname;
    std::ifstream fcontent(fname.c_str(), std::ios::in);
    std::string text_line;
    while(getline(fcontent, text_line, '\n')) {
        lines_of_text->push_back(text_line);
    }
}


int main() {
    TextQuery tq;
    tq.retrieve_text();
    return 0;
}

我在 MacOS 上使用 g++ 4.2.1。

标签: c++segmentation-faultcin

解决方案


您声明了一个成员指针但没有分配对象

std::vector<std::string> *lines_of_text;

但是你为什么要使用指针?您可以将其声明为成员对象

std::vector<std::string> lines_of_text;

推荐阅读