I’m trying to simply record a file’s properties by making a vector of objects. It works just fine when the vector is a vector of objects, but when the vector is object pointers, the outcome is a bunch of garbage value.
the outcome with object vector:
1 Computer Engineering
2 Electrical Engineering
3 Chemical Engineering
the outcome with object pointer vector:
3 �Kҍa�c�� feering
3 �Kҍa�c�� feering
3 �Kҍa�c�� feering
and it changes every time.
this is the piece of code that produces that error:
#include <iostream>
#include <vector>
#include <utility>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;
class Major
{
private:
int id;
string name;
public:
Major(int major_id, string major_name)
{
id = major_id;
name = major_name;
}
void revealMajorInfo()
{
cout << id << ' ' << name << endl;
}
};
int main(int argc, char *argv[])
{
string current_exec_name = argv[0];
vector<string> file_paths;
if (argc > 1)
{
file_paths.assign(argv + 1, argv + argc);
}
fstream major_file;
major_file.open(file_paths[0], ios::in);
vector<string> properties;
vector<vector<string>> properties_details;
string line, word;
while (getline(major_file, line))
{
properties.clear();
stringstream major_line(line);
while (getline(major_line, word, ','))
{
properties.push_back(word);
}
properties_details.push_back(properties);
}
vector<Major *> majors;
for (int i = 0; i < properties_details.size(); i++)
{
Major major1(stoi(properties_details[i][0]), properties_details[i][1]);
major1.revealMajorInfo();
majors.push_back(&major1);
}
for(int j = 0; j < majors.size(); j++)
{
majors[j]->revealMajorInfo();
}
}
and this is the code that doesn’t produce an error:
#include <iostream>
#include <vector>
#include <utility>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;
class Major
{
private:
int id;
string name;
public:
Major(int major_id, string major_name)
{
id = major_id;
name = major_name;
}
void revealMajorInfo()
{
cout << id << ' ' << name << endl;
}
};
int main(int argc, char *argv[])
{
string current_exec_name = argv[0];
vector<string> file_paths;
if (argc > 1)
{
file_paths.assign(argv + 1, argv + argc);
}
fstream major_file;
major_file.open(file_paths[0], ios::in);
vector<string> properties;
vector<vector<string>> properties_details;
string line, word;
while (getline(major_file, line))
{
properties.clear();
stringstream major_line(line);
while (getline(major_line, word, ','))
{
properties.push_back(word);
}
}
Major major1(stoi(properties_details[0]), properties_details[1]);
major1.revealMajorInfo();
Major* major2 = &major1;
major2->revealMajorinfor();
}
any help would be appreciated.
New contributor
Tori Myers is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.