Reputation:
I know this question as been asked before, but it was never answered and my situation is different
I am creating a student struct to store student information:
struct Student {
std::string m_firstname = "";
std::string m_lastname = "";
int m_testscore = {0};
char m_grade;
};
I want to read the student name from a text file into an array, I have a function for that:
// 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;
}
}
When I run the program, everything works and I get all the student information from the file displayed in a console, but then I also get an error "Unable to read memory" and "Access violation", I set a break point and after stepping through the code I found out that the error occurs when I am accessing the file stream, here is what the debugger says
std::basic_ios<char,std::char_traits<char> > <Unable to read memory>
Text file:
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
Upvotes: 0
Views: 499
Reputation:
The error occurred because I was promising to return a type that was never returned with the read_data() function. it should be:
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();
}
Upvotes: 1