c++ - 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。
解决方案
您声明了一个成员指针但没有分配对象
std::vector<std::string> *lines_of_text;
但是你为什么要使用指针?您可以将其声明为成员对象
std::vector<std::string> lines_of_text;
推荐阅读
- r - 如何使用 tmap_mode "plot" 缩小
- kotlin - Kotlin 扩展函数生成错误的字节码
- javascript - 创建标签开关
- node.js - 将回调的值分配给常量
- django-rest-framework - 缓存外部 API 调用 - Django
- ios - 重命名的深层链接 URL 不再打开我更新的 iOS 应用程序
- linux - 如何从文本文件中打印重复值的全名?
- python - 如何在 PyGame 画布上从 PyRealSense2 绘制视频帧?
- bash - 仅当名称中存在字符串时才复制目录和子目录
- php - Symfony 5.1.8 忽略来自 .env.test / .env.test.local 的覆盖