How to read file into class in C++? - c++

I am reading File that contains
Boss, level, Specials,
"FireMen", 3, "Flame,Thrower", Fire,Breath
"Medusa", 6, "Snake,Poison"
"Hype", 10, "One,punch,Knock", Fly,Kick, "Dragon,Breath"
I am trying to read it into class with objects boss, level and specials
I am having problem reading from file since I split each by words by comma but it read specials like Flame,Thrower as separate due to comma in between them. How can I combine specials rather then splitting by commas so that it read Flame Thrower rather then Flame and thrower separately.
Also some specials are in quotation others are not.
I have been stuck at reading this rather complicated file. If anyone has time to read through my code and fix 10s of errors that I am getting would greatly be appreciated, Thank You
(What I did doesn't make much sense since this is my one month into C++ so still newbie and progressing)
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <iomanip>
#include "Boss.h"
using namespace std;
vector <Boss*> Info;
Boss* parseLine(string str)
{
vector<string> store;
string smt = " ";
Boss* values = nullptr;
if (smt != "")
{
(store.push_back(smt));
}
for (int i = 0; i < (int)str.size(); i++)
{
char ch = str[i];
if (ch != ',')
{
smt = smt + ch;
}
else
{
store.push_back(smt);
smt = "";
}
}
values = new Boss(store[0], stoi(store[1]), store[2]);
Name = store[0];
Level = store[1];
Specials = store[2];
return values;
}
bool readFile()
{
std::ifstream myFile("Bosses.txt");
if (!myFile.is_open())
{
cout << "fAILED" << "\n";
return false;
}
string str;
int i = 0;
while (std::getline(myFile, str))
{
cout << str << endl;
if (str[0] != '/')
{
Boss* Boss = parseLine(str);
result.push_back(Boss);
}
}
return true;
}
int main()
{
std::cout << "Read file\n;";
bool data = readFile();
for (Boss* t : result)
{
delete t;
}
And Class
#include <string>
#include <vector>
class Boss {
std::string Name;
int Level;
std::vector<std::string> Specials;
Boss(std::string Name, int Level, std::vector<std::string> Specials);
~Boss();
Boss(Boss& b);
void setName(std::string Name);
void setLevel(int Level);
};
Boss::Boss(std::string Name, int Level, std::vector<std::string> Specials)
{
this->Name= Name;
this->Level = Level;
this->Specials = Specials;
}
Boss::~Boss() {}
Boss::Boss(Boss& b)
{
Name = b.Name;
Level = b.Level;
Specials = b.Specials;
}
void Boss::setName(std::string Name) {
this->Name = Name;
}
void Boss::setLevel(int Level)
{
this->Level = Level;
}

This code reads your file and stores the data in the std::vector Info using stringstreams and other things to parse.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <iomanip>
#include <sstream>
using namespace std;
class Boss {
std::string Name;
int Level;
std::vector<std::string> Specials;
public:
Boss(std::string n, int l, std::vector<std::string> s)
{
this->Name = n;
this->Level = l;
this->Specials = s;
};
~Boss() {};
Boss(const Boss& b) {
this->Name = b.Name;
this->Level = b.Level;
this->Specials = b.Specials;
};
Boss() {};
Boss operator= (Boss b) {
this->Name = b.Name;
this->Level = b.Level;
this->Specials = b.Specials;
return b;
}
void setName(std::string n) { Name = n; };
void setLevel(int l) { Level = l; };
void setSpecials(std::vector<std::string> s) {Specials = s;}
std::string getName() const { return Name; }
int getLevel() const { return Level; }
std::vector<std::string> getSpecials() const { return Specials; }
};
vector <Boss> Info;
Boss parseLine(string str)
{
vector<string> store;
string smt;
stringstream evaluator;
Boss value;
evaluator << str; //put our string into evaluator
{
char double_quote_remover;
evaluator >> double_quote_remover; //remove the first double quote
getline(evaluator, smt, '"'); //get the name until the next double quote
char comma_remover;
evaluator >> comma_remover; //remove the comma
}
value.setName(smt); //put smt into the Boss's name
{
int Level;
evaluator >> Level; //get an int from our string
value.setLevel(Level); //put our int into our Boss
}
char curr;
while (evaluator >> curr && curr != ','); //get the comma after the int
smt = ""; //reset
curr = ' '; //reset
while (evaluator >> curr) { //while we read chars into curr
if (isalpha(curr)) { evaluator.putback(curr); curr = ','; } //if the char is a letter, put it back
if (curr == '\"') getline(evaluator,smt,'\"'); //if the char is a double quote, read until we reach another
else if (curr == ',') getline(evaluator,smt,','); //if the char is a comma, read until we get another
if (smt != "") //if the string is not null, put it in store
store.push_back(smt);
smt = ""; //reset
}
value.setSpecials(store); //put store into our Boss
return value; //return our boss
}
bool readFile()
{
std::ifstream myFile("Bosses.txt");
if (!myFile.is_open())
{
cout << "FAILED" << "\n";
return false;
}
string str;
getline(myFile, str); //for the first line, which we don't need
int i = 0;
while (std::getline(myFile, str))
{
Boss Boss = parseLine(str);
Info.push_back(Boss);
}
return true;
}
int main()
{
bool data = readFile();
}
This should work. I have tested it thouroughly. Inform me of any errors.
Note: There was no need for pointers that were in your original code.

Related

Why do I get a segmentation fault when fetching this variable?

I am pulling names as strings from a file, create a Person *p object, and put it into an array.
Then to search the array for a name but when I try to fetch the name I get a segmentation fault.
Why is this segmentation fault happening, and what can I do to fix it?
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string firstName;
string lastName;
string phoneNumber;
public:
Person();
Person(string f, string l, string n);
~Person(void);
void setName()
{
}
string getFirstName()
{
return firstName;
}
string getLastName()
{
return lastName;
}
string getNumber() { return phoneNumber; }
void print();
};
Array creation.
{
ifstream file;
file.open("phonebook.txt");
if (!file.is_open()) //Check for File Error.
{
cerr << "Failed to open file" << endl;
exit(1);
}
//Get Array Size
string line;
while (getline(file, line))
{
count++;
}
file.close();
//Create an array
Person *arrList[count];
buildArray(arrList, count);
if (uInput == "a" || uInput == "A") //To add
{
int x = addPerson();
if (x == 1)
{
count++;
}
delete[] arrList;
}
void buildArray(Person *arr[], int size)
{
string f, l, n;
ifstream file;
file.open("phonebook.txt");
for (int i = 0; i < size; i++)
{
file >> f >> l >> n;
Person *p = new Person(f, l, n);
arr[i] = p;
delete p;
}
}
The search, This is the part that has the trouble. I have tried a few different things including creating 2 Persons, and comparing their parts but whenever it goes into the .h it can not return the name.
if (uInput == "s" || uInput == "S")
{ //To Search
string f, l;
cout << "Find Who (Firstname Lastname) " << endl;
cin >> f >> l;
Person *n = new Person(f, l, "");
int i = 0;
bool found = false;
while (i <= count && found == false)
{
Person *p = new Person("", "", "");
p = arrList[i];
if (p->getFirstName() == n->getFirstName() && p->getLastName() == n->getLastName())
{
arrList[i]->print();
found = true;
delete p;
delete n;
}
i++;
}
while (i == count && found == false)
{
cout << "No results found. " << endl;
found = true;
}
}

why whould this while loop won't stop? c++

This is a code for reading in .txt file and spliting it by : and printing out the result. But I got stuck on the while-loop. This is my code.
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
string* split(const string& str, const string& delim) {
string* string_list = new string[10];
int idx = 0;
char *token = strtok(const_cast<char*>(str.c_str()), delim.c_str());
while (token != NULL) {
string_list[idx] = token;
token = strtok(NULL, delim.c_str());
++idx;
}
return string_list;
}
struct Item {
string name;
string age;
string id;
string subject[10];
};
struct Item* create_item() {
struct Item* pitem = new Item;
return pitem;
};
void insert_item(struct Item *prev_item, struct Item *item) {
item = (prev_item + 5);
}
int main() {
string student, student2;
string *string_list, *subject, *string_list2, *subject2;
struct Item* pstudent, *pstudent2;
ifstream fin;
fin.open("input.txt");
fin >> student;
while (student != "\n") {
string_list = split(student, ":");
pstudent = create_item();
pstudent->name = *string_list;
pstudent->age = *(string_list + 1);
pstudent->id = *(string_list + 2);
subject = split(*(string_list + 3), ",");
for (int i = 0; i < 10; i++) {
if (*(subject + i) != "") {
pstudent->subject[i] = *(subject + i);
}
}
cout << *(string_list+1) << endl;
fin >> student2;
string_list = split(student2, ":");
pstudent2 = create_item();
insert_item(pstudent, pstudent2);
pstudent2->name = *(string_list);
pstudent2->age = *(string_list + 1);
pstudent2->id = *(string_list + 2);
subject2 = split(*(string_list + 3), ",");
for (int i = 0; i < 10; i++) {
if (*(subject2 + i) != "") {
pstudent2->subject[i] = *(subject2 + i);
}
}
}
cout << pstudent2->name << endl;
fin.close();
return 0;
}
I am still working on this code, but the while-loop in the main() will not stop. I wanted it to stop when the input.txt file input is a new line.
input.txt is
Mary:20:287:Math,Algorithm\n
Tom:21:202:Math,English\n
Hee:20:256:Math
thanks in advance!
Don't try to process more than one student in the body of the loop.
Rather than trying to write a linked-list type, use an existing collection type.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using strings_view = std::vector<std::string_view>;
strings_view split(std::string_view str, char delim) {
strings_view view;
while (str.size())
{
auto pos = str.find(delim);
view.push_back(str.substr(0, pos - 1));
str = str.substr(pos + 1);
}
return view;
}
struct Item {
std::string name;
std::string age;
std::string id;
std::vector<std::string> subject;
};
int main() {
std::vector<Item> students;
std::ifstream fin("input.txt");
for (std::string line; get_line(fin, line);) {
strings_view view = split(line, ':');
Item student;
student.name = view[0];
student.age = view[1];
student.id = view[2];
string_view subject = split(view[3], ',')
student.subject.assign(subject.begin(), subject.end());
students.push_back(student);
}
std::cout << students[1].name << std::endl;
return 0;
}

Printing from Trie

I have built a trie in C++ designed to hold words of sentences. Each sentence will have a weight which determines the order in which they should be output. I have several recursive functions that call other recursive functions, and the dilemma I am facing is that I want to print my list only once.
Basically my get function calls the printFromNode function which creates the vector of pairs p that I want to sort and print. If someone could point me in the right direction in how to do that it would be much appreciated.
Code:
Trie.cpp:
//#include "Trie.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <sstream>
#include <stack>
using namespace std;
class Node
{
private:
string word = "";
bool endOfSentence = false;
int weight = -1;
public:
vector<Node> children = {};
Node() {
this->setWord("");
}
Node(string s){
this->setWord(s);
}
string getWord(){
return this->word;
}
void setWord(string s) {
this->word = s;
}
void setEOS(){
this->endOfSentence = true;
}
void setWeight(int weight){
this->weight = weight;
}
int getWeight() {
return this->weight;
}
};
class Trie
{
public:
Node root;
void add(vector<string> phrase, int weight, Node* n){
Node* current = n;
int w = weight;
int found = -1;
for (int i = 0; i < current->children.size(); i++) {
if (phrase[0] == current->children[i].getWord()) {
found = i;
}
}
if (found > -1) {
current = &current->children[found];
phrase.erase(phrase.begin());
add(phrase, w, current);
}
else {
addPhrase(phrase, w, current);
}
}
void addPhrase(vector<string> phrase, int weight, Node* n) {
Node* current = n;
for (int i = 0; i < phrase.size(); i++) {
Node temp = *new Node(phrase[i]);
current->children.push_back(temp);
current = &current->children.back();
if (i == phrase.size() - 1) {
current->setEOS();
current->setWeight(weight);
}
}
}
void get(vector<string> search) {
Node* current = &this->root;
get(search, current);
}
void get(vector<string> search, Node* n) {
Node* current = n;
int found = -1;
//test search size
if (search.size() == 0) {
cout << "Please enter a valid search" << endl;
}
for (int i = 0; i < current->children.size(); i++) {
if (search[0] == current->children[i].getWord()) {
found = i;
}
}
if (found > -1 && search.size() == 1) {
current = &current->children[found];
printFromNode(*current);
maxNode(*current);
}
else if (found > -1 && search.size() != 1) {
current = &current->children[found];
search.erase(search.begin());
get(search, current);
}
else {
cout << "Not Found" << endl;
}
}
void printOutput(vector<pair<int,string>> p){
sort(p.begin(), p.end());
cout << p.size() << endl;
for (int i = 0; i < p.size(); i++) {
cout << p[i].second << " " << endl;
}
}
void printFromNode(Node n) {
vector<string> phrase = {};
vector <pair < int, string>> final = {};
printFromNode(n,phrase,final);
}
void printFromNode(Node n, vector<string> &v, vector<pair<int,string>> &p) {
string output;
if (n.getWord() == "") {
return;
}
for (int i = 0; i < n.children.size(); i++) {
if (n.children[i].getWeight() > 0) {
for (int i = 0; i < v.size(); i++)
{
output.append(v[i] + " ");
}
output.append(n.children[i].getWord());
p.push_back(make_pair(n.children[i].getWeight(), output));
}
v.push_back(n.children[i].getWord());
printFromNode(n.children[i], v, p);
v.pop_back();
sort(p.begin(), p.end());
}
return;
}
void maxNode(Node n) {
int max = 0;
int index = 0;
int temp = 0;
for (int i = 0; i < n.children.size(); i++) {
temp = n.children[i].children.size();
if (temp > max) {
max = temp;
index = i;
}
}
cout << n.children[index].getWord() << " " << max << endl;
}
};
Main.cpp:
#include "Trie.cpp"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char* argv[]) {
// Initialize trie up here
Trie myTrie = *new Trie();
// parse input lines until I find newline
for(string line; getline(cin, line) && line.compare(""); ) {
stringstream ss(line);
string string_weight;
ss >> string_weight;
int weight = stoi(string_weight);
// I am just going to put these words into a vector
// you probably want to put them in your trie
vector<string> phrase = {};
for(string word; ss >> word;) {
phrase.push_back(word);
}
myTrie.add(phrase, weight, &myTrie.root);
vector<string> ans = {};
}
// parse query line
string query;
getline(cin, query);
stringstream ss(query);
vector<string> search = {};
for (string query; ss >> query;) {
search.push_back(query);
}
myTrie.get(search);
return 0;
}
You can remove recursive methods, and doing something like the following:
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <set>
class Node
{
public:
bool endOfSentence = false;
std::set<int> weights;
std::map<std::string, Node> children;
Node() = default;
const Node* get(const std::string& word) const
{
auto it = children.find(word);
if (it == children.end()) {
return nullptr;
}
return &it->second;
}
auto find_by_weight(int weight) const
{
return std::find_if(children.begin(),
children.end(),
[=](const auto& p){ return p.second.weights.count(weight);});
}
};
class Trie
{
Node root;
public:
void add(int weight, const std::vector<std::string>& phrase)
{
Node* node = &root;
for (const auto& word : phrase) {
node->weights.insert(weight);
node = &node->children[word];
}
node->weights.insert(weight);
node->endOfSentence = true;
}
bool contains(const std::vector<std::string>& phrase) const
{
const Node* node = &root;
for (const auto& word : phrase) {
node = node->get(word);
if (node == nullptr) {
return false;
}
}
return node->endOfSentence;
}
void print(int weight) const
{
const Node* node = &root;
const char* sep = "";
while (node) {
const auto it = node->find_by_weight(weight);
if (it == node->children.end()) {
break;
}
std::cout << sep << it->first;
sep = " ";
node = &it->second;
}
std::cout << std::endl;
}
void print_all() const
{
for (int i : root.weights) {
print(i);
}
}
};
And usage/Test:
int main(int argc, char* argv[]) {
const std::vector<std::vector<std::string>> sentences = {
{"My", "name", "is", "John"},
{"My", "house", "is", "small"},
{"Hello", "world"},
{"Hello", "world", "!"}
};
Trie trie;
int i = 0;
for (const auto& sentence : sentences) {
trie.add(i, sentence);
++i;
}
const std::vector<std::vector<std::string>> queries = {
{"My", "name", "is", "John"},
{"My", "house"},
{"Hello", "world"}
};
for (const auto& query : queries) {
std::cout << trie.contains(query) << std::endl;
}
trie.print_all();
}
Demo

C++ Error C2451 conditional String is illegal

i'm fairly new to C++.
I want to write a Program/Function that checks a string input (from console or other source, not important here) if is already in an array. If it's not then it should be written into array. Otherwise do nothing.
My Problem is the for loop and if the if condition. What am I missing?
#include <iostream>
#include <string>
#include <fstream>
#include <stdio.h>
using namespace std;
typedef struct {
string id[10];
string foo1[10];
string type[10];
string func[10];
}Device;
int main() {
Device fooDevice;
string mystring;
int i = 0;
mystring = "foo";
ofstream temp;
temp.open("temp.txt", ios::out | ios::app);
for (fooDevice.id[i]; fooDevice.id[9]; i++) {
if (fooDevice.id[i] != mystring) {
fooDevice.id[i] = mystring;
temp << mystring << endl;
} else {
//do nothing
}
}
return 0;
}
The problem is the structure of your for loop. I'm not sure what you think your condition means, but here's how it should look:
for (std::size_t i = 0; i < 10; ++i) {
This increments the index value i from 0 to 9 (inclusive). You can then check the value of fooDevice[i].
At the moment, it seems you are trying to overwrite every element of the array with the new string. I'm not sure how you know how full the array is at any given time. Let's suppose you stop when you get to the first empty string:
for (std::size_t i = 0; i < 10; ++i) {
if (myString == fooDevice.id[i]) {
// already there, stop looping
break;
}
else if (fooDevice.id[i].empty()) {
// none of the currently set elements matches
fooDevice.id[i] = myString;
temp << myString << '\n';
break;
}
}
You could also replace this with a range-based-for:
for (auto& deviceId: fooDevice.id) {
if (myString == deviceId) {
// already there, stop looping
break;
}
else if (deviceId.empty()) {
// none of the currently set elements matches
deviceId = myString;
temp << myString << '\n';
break;
}
}
Better yet, use a std::vector with std::find from the <algorithm> header. (Warning: untested code):
struct Device {
// ...
std::vector<std::string> id;
// ...
};
// ...
auto foundId = std::find(fooDevice.id.begin(), fooDevice.id.end(), myString);
if (fooDevice.id.end() == foundId) {
// not already there
fooDevice.id.push_back(myString);
temp << myString << '\n';
}
It seems you are a bit confused about the difference between C and C++ as well:
The C++ version of <stdio.h> is <cstdio>, but you don't need it here at all (and you usually don't in a C++ program).
You don't need to typedef the name of a struct in C++, just do struct Device { ... };
And regarding C++ style, please reconsider your use of what are often considered bad practices: using namespace std; and endl.
for (fooDevice.id[i]; fooDevice.id[9]; i++) seems no scence. I think you want:
for(; i<9; ++i)
You can't use a string value as a loop condition. Only expressions that evaluate to booleans.
Also, you are also not initializing the device arrays before searching them.
Try something more like this:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Device {
string id[10];
string foo1[10];
string type[10];
string func[10];
};
int main() {
Device fooDevice;
string mystring;
// fill fooDevice as needed...
mystring = "foo";
ofstream temp;
temp.open("temp.txt", ios::out | ios::app);
bool found = false;
int idx_available = -1;
for (int i = 0; i < 10; ++i) {
if (fooDevice.id[i] == mystring) {
//do nothing
found = true;
break;
}
if ((idx_available == -1) && fooDevice.id[i].empty())
idx_available = i;
}
if ((!found) && (idx_available != -1)) {
fooDevice.id[idx_available] = mystring;
temp << mystring << endl;
}
return 0;
}
Which would be better handled with some rewriting:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
struct Device {
std::string id;
std::string foo1;
std::string type;
std::string func;
};
struct isDeviceId {
const std::string &m_id;
isDeviceId(const std::string &id) : m_id(id) {
}
bool operator()(const Device &device) {
return (device.id == m_id);
}
};
int main() {
std::vector<Device> devices;
std::string mystring;
// fill devices as needed...
mystring = "foo";
if (std::find_if(devices.begin(), devices.end(), isDeviceId(mystring)) == devices.end()) {
Device device;
device.id = mystring;
devices.push_back(device);
std::ofstream temp;
temp.open("temp.txt", std::ios::out | std::ios::app);
temp << mystring << std::endl;
}
return 0;
}
Alternatively, in C++11 and later:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
struct Device {
std::string id;
std::string foo1;
std::string type;
std::string func;
};
int main() {
std::vector<Device> devices;
std::string mystring;
// fill devices as needed...
mystring = "foo";
if (std::find_if(devices.begin(), devices.end(),
[mystring&](const Device &device) { return (device.id == mystring); }
) == devices.end()) {
devices.emplace_back();
devices.back().id = mystring;
// or, in C++17:
// devices.emplace_back().id = mystring;
std::ofstream temp;
temp.open("temp.txt", std::ios::out | std::ios::app);
temp << mystring << std::endl;
}
return 0;
}

What's wrong with my logic? My Vector or an object doesn't push_back a new object. Stays at size of 0

I worked on this all day and am stuck on my logic in how I approached this problem. Whenever I have a Vector<class> blah. And I try to blah.push_back(class()), it doesn't, update or work.
I've been researching and I think it has to do with pointers and references. I tried changing Vector<Student> blah to Vector<Student*> blah, and using 'new' Student() when I'm pushing it back, but it still yields the same result. I think I'm defining the vectors wrong.
#include "std_lib_facilities.h"
using namespace std;
class Student
{
public:
string first_name;
string last_name;
string major;
int student_id;
Student() {};
Student(int no, string name1, string name2, string majorin)
{
first_name = name1;
last_name = name2;
student_id = no;
major = majorin;
}
};
class Course
{
public:
Vector<Student> Students;
int max_enrollment;
int course_id;
string course_title;
Course() {};
Course(int no_in,int max_in,string title_in)
{
max_enrollment=max_in;
course_title=title_in;
course_id=no_in;
}
};
unsigned int split(const std::string &txt, vector<std::string> &strs, char ch)
{
unsigned int pos = txt.find( ch );
unsigned int initialPos = 0;
strs.clear();
// Decompose statement
while( pos != std::string::npos ) {
strs.push_back( txt.substr( initialPos, pos - initialPos + 1 ) );
initialPos = pos + 1;
pos = txt.find( ch, initialPos );
}
// Add the last one
strs.push_back( txt.substr( initialPos, std::min( pos, txt.size() ) - initialPos + 1 ) );
return strs.size();
}
class University
{
public:
Vector<Student> studentlist;
Vector<Course> courselist;
University() {};
void Parse(string input)
{
//Case Statements
vector<string> temp;
split( input, temp, ' ' );
cout<<temp[0];
if (temp[0]=="S ")
{
//Add Student to University
//Student* myStudent=new );
cout<<studentlist.size()<<endl;
//Student(atoi(temp[1].c_str()),temp[2],temp[3],temp[4])
studentlist.push_back(Student());
}
else if (temp[0]=="C")
{
//Add Course to University
Course myCourse=Course(atoi(temp[1].c_str()),atoi(temp[2].c_str()),temp[3]);
courselist.push_back(myCourse);
}
else if (temp[0]=="L")
{
//Add Student to Course list
//Not Implemented-Find Course by temp[1] which is a int
for (int i=0;i<courselist.size();i++)
{
if (courselist.at(i).course_id==atoi(temp[1].c_str()))
{
courselist.at(i).max_enrollment=atoi(temp[1].c_str());
}
}
}
else if (temp[0]=="A")
{
for (int i=0;i<courselist.size();i++)
{
if (courselist.at(i).course_id==atoi(temp[1].c_str()))
{
for (int j=0;j<studentlist.size();j++)
{
if (studentlist.at(j).student_id==atoi(temp[1].c_str()))
{
Student mystudent=studentlist.at(j);
courselist.at(i).Students.push_back(mystudent);
}
}
}
}
}
else if (temp[0]=="D")
{
for (int i=0;i<courselist.size();i++)
{
if (courselist.at(i).course_id==atoi(temp[1].c_str()))
{
for (int j=0;j<courselist.at(i).Students.size();j++)
{
if (courselist.at(i).Students.at(j).student_id==atoi(temp[1].c_str()))
{
//Student mystudent=courselist.at(i).Students.at(j);
courselist.at(i).Students.erase(courselist.at(i).Students.begin()+j);
}
}
}
}
}
else if (temp[0]=="PS")
{
cout<<"--Student Report--\n";
}
else if (temp[0]=="PC")
{
cout<<"--Student Report--\n";
for (int i=0;i<courselist.size();i++)
{
for (int j=0;j<courselist.at(i).Students.size();j++)
{
string first_name=courselist.at(i).Students.at(j).first_name;
string last_name=courselist.at(i).Students.at(j).last_name;
string major=courselist.at(i).Students.at(j).major;
//Waiting List var
cout<<first_name<<" "<<last_name<<" "<<major<<"\n";
}
}
}
}
};
int main(int argc, char *argv[])
{
string input;
while(1==1)
{
cout<<"Command:: ";
getline(cin,input);
//cout<<input;
University myUniversity;
myUniversity.Parse(input); //Input is in the format X Name Name etc etc. Arguments separated by spaces
cout<<"DEBUG:"<<myUniversity.studentlist.size();
}
return 0;
}
Simple Error! Can't believe you spent so long on this! Haha.
You defined your University inside your while loop!
I'm not familiar with C++ (learning myself), but I think it should also be done using pointers and references and the keyword 'new'.
Can someone explain the difference between the way he's doing it and other ways I've seen where people use Student mystudent=new Student(); etc etc