I have been working on just importing from a file into my objects for 2+ days and read the book, searched the internet and basically tried everything I could think of.. so here is a last ditch (of course I'll never give up haha). >>>I have a class ItemClass for software objects, which I place in a vector eventually to be updated and written back to the file. My perfect outcome would be to read the contents of the file directly into the vector of software objects but right now I just want to get the contents of the file correctly. The file I am reading from is thus:
Adobe Photoshop
CS5
5 21 580
Norton Utilities
n/a
1 10 50
Norton System Works
2009
3 6 50
Visual Studio Professional
2010
4 19 700
Microsoft Office
2010
6 27 150
Here is the code that is not behaving as expected:
int main() {
//declare new classes to play with file input/output
ItemClass pshop;
ItemClass nU;
ItemClass sW;
ItemClass vsP;
//declare a vector to hold the objects for later sorting and placing into a tree structure
vector<ItemClass> classVector;
ifstream file;
file.open("software.txt");
if (file.fail()) {
cout << "Error reading from file." << endl;
}
//edited code
std::string kqpline;
getline(file, kqpline);
std::istringstream kqpstream(kqpline);
kqpstream >> k >> q >> p;
pshop.setItem(k, n, v, q, p);
getline(file, n);
getline(file, v);
getline(file, kqpline);
kqpstream >> k >> q >> p;
nU.setItem(k, n, v, q, p);
nU.setItem(k, n, v, q, p); //end edited code- this interface is killing me so I didn't update the rest of my code- but it looked like this
mark = file.tellg();
file.seekg(mark);
getline(file, n);
getline(file, v);
file >> k;
file >> q;
file >> p;
sW.setItem(k, n, v, q, p);
mark = file.tellg();
file.seekg(mark);
getline(file, n);
getline(file, v);
file >> k;
file >> q;
file >> p;
vsP.setItem(k, n, v, q, p);
file.close();
cout << "here is the object we extracted from 'file': " << endl;
pshop.printItem();
nU.printItem();
sW.printItem();
vsP.printItem();
classVector.push_back(pshop);
classVector.push_back(nortonU);
classVector.push_back(vsPro);
classVector.push_back(nSysWorks);
Here is the output:
Key: 5
Name: Adobe Photoshop
Version: CS5
Quantity: 21
Price: $580
Key: 1
Name: lities
Version: n/a
Quantity: 10
Price: $50
Key: 3
Name: System Works
Version: 2009
Quantity: 6
Price: $50
Key: 4
Name: al Studio Professional
Version: 2010
Quantity: 19
Price: $700
I tried cin.ignore() to try to get the rest of the titles that were truncated and also cin.clear() and you can probably guess that it just made things worse. I understand this is pretty basic stuff.Thank you for helping me over this hump.