代码是:
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。
最佳答案
声明一个成员指针但不分配对象
std::vector<std::string> *lines_of_text;
但是为什么要使用指针呢?您可以将其声明为成员对象
std::vector<std::string> lines_of_text;
关于C++ cin 段错误 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50443262/