使用fstream访问文件时无法读取内存
Unable to read memory when accessing file using fstream
我知道以前有人问过这个问题,但从来没有人回答过,我的情况与不同
我正在创建一个学生结构来存储学生信息:
struct Student {
std::string m_firstname = "";
std::string m_lastname = "";
int m_testscore = {0};
char m_grade;
};
我想把学生的名字从一个文本文件中读取到一个数组中,我有一个函数:
// Read student data into an array
Student read_data() {
Student students[20];
// Open input file
std::ifstream input("name.txt", std::ios::in);
// Check if file is good
if (!input) {
std::cout << "Error occurred" << std::endl;
exit(-1);
}
// Read data from file
for (int i = 0; i < 20; i++) {
input >> students[i].m_firstname >> students[i].m_lastname;
}
// Display data
for (size_t i = 0; i < 20; i++) {
std::cout << students[i].m_firstname << " " << students[i].m_lastname << std::endl;
}
}
当我运行该程序时,一切都正常,我从控制台中显示的文件中获得所有学生信息,但随后我也会收到一个错误"无法读取内存";以及";访问违规">,我设置了一个断点,在遍历代码后,我发现在访问文件流时发生了错误,以下是调试器所说的
std::basic_ios<char,std::char_traits<char> > <Unable to read memory>
文本文件:
Guillermo Mora
Hugh Hanna
Isaac Atkinson
Teodoro Macdonald
Esperanza Sawyer
Werner Daugherty
Fran Middleton
Alvin Rowland
Richie Patterson
Mario Simpson
Lewis Wolf
Maria Yates
Ernest Cuevas
Andrea Bernard
Nigel Carlson
Dennis Owen
Ezra Jacobs
Sarah Francis
Jarvis Peterson
Erika Harmon
发生错误是因为我承诺返回一个从未用read_data((函数返回的类型。应该是:
void read_data() {
Student students[20];
// Open input file
std::ifstream input("name.txt", std::ios::in);
// Check if file is good
if (!input) {
std::cout << "Error occurred" << std::endl;
exit(-1);
}
// Read data from file
for (int i = 0; i < 20; i++) {
input >> students[i].m_firstname >> students[i].m_lastname;
}
// Display data
for (size_t i = 0; i < 20; i++) {
std::cout << students[i].m_firstname << " " << students[i].m_lastname << std::endl;
}
input.close();
}
相关文章:
- 我可以在没有任何锁的情况下从不同的线程读取内存缓冲区吗?
- SAP Netweaver.C++ 错误:无法读取内存
- c++ 结构指针在初始化为 NULL 时无法读取内存
- GDB Python模块读取内存内容
- 内存池和<无法读取内存>
- 读取内存值(实时)最佳实践
- C++无法读取内存地址
- 构造函数问题<无法读取内存>
- C 螺纹池具有共享仅读取内存
- C++ 读取内存地址/指针和偏移量
- C++字符串无法读取内存
- 调用函数时,c++无法使用自定义类读取内存
- 无法读取内存以删除对象数组
- ConstantStruct或ConstantArray读取内存内容
- 如何在可视C++中读取内存地址
- C++:从注入的DLL读取内存的好方法是什么?
- C++ 对象的实例无法读取内存
- <无法读取内存> c++
- 内核驱动程序读取内存未发送整个字符串
- 在C++中嵌入 Python 的错误:无法读取内存