Reputation:
I am brand new to C++ and pretty new to programming overall. I am working on a class assignment in C++ to manage a DVD store with 10 DVDs. The goal is to print out information about each DVD by using abstract data types and using an array of ten DVD instances by pulling from a text file.
So far, I have been able to import the text file, reads it line by line, splits each line into 4 strings (title, genre, rating, description). Now I am trying to connect it to the class function I have made to actually connect each string to class DVD - Title, genre, rating, description.
I am not understanding classes well, and have done my best to read about them in my text, in C++ primer, and online but they aren't quite clicking yet.
Do I make 10 class instances, and set each class instance to be equal to each one of my strings?
Probably best to show some code:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
class Dvd {
public:
string title, genre, rating, description;
string print(void) {
return (title + genre + rating + description + "\n");
} //Dont even know if this is right... My best first attempt at class creation...
};
int main() {
Dvd one, two, three, four, five, six, seven, eight, nine, ten; //initialize class objects
string line, word, templist[10];
ifstream in("dvd_list.txt");
for(int i = 0; i < 10; i++) {
getline(in, line);
templist[i] = line; //read the file into a line
string components;
istringstream temp(line);
while(getline(temp, components, ';')) { // Splits line into strings
for(int k = 0; k < 4; k++) {
//wanting to bind strings to class objects here
} //My thought was to use if(k = 0), --> one.title = component
} // if(k = 1) --> one.genre etc....
}
}
So, at this point, it was my idea to tie classes to the individual component strings with the last for loop (K). I am trying to understand how to actually tie class objects to strings. I think the code will eventually look something like:
one.title = ....
one.genre = ....
one.rating = ....
But I am wondering if there is a better way to do this (for loop or something)? or just manually write it all out until I get there (this seems wrong, but I don't know how to get from here to efficient yet).
Last: I also know using namespace....
isnt considered great practice, but the book and course I am working through encouraged this until about half way through this section, and are transitioning to std::.... but for now, I need to focus on understanding classes and getting it to work before shifting that mindset.
Thanks for your help!
Upvotes: 0
Views: 106
Reputation: 11430
You want to have either:
Dvd myDvds[10];
or
std::vector<Dvd> dvdVect(10);
Then you can access them with myDvds[i]
or dvdVect[i]
.
Upvotes: 1