#include <vector>
#include <sstream> // sstream also include <string>, so no need to add it.
#include <fstream>
#include <iostream>
usingnamespace std;
int main()
{
vector<string> food;
vector<int> serVings;
vector<int> pieces;
vector<string> amOunt;
vector <string> ingredient;
ifstream inFile;
inFile.open ("recipe0.dat");
if(!inFile)
cout << "No file found";
while(!inFile.eof())
{
string Nam;
int servings;
string tempPiece;
int piece;
string AmT;
string ingred;
getline(inFile, Nam);
inFile >> servings;
getline( inFile, tempPiece, ' ' );
getline(inFile, AmT, ' ');
getline(inFile, ingred);
// Create a stringstream object and pass it the string.
stringstream ss( tempPiece );
// If the conversion to int fails, break from the loop.
if( ! ( ss >> piece ) )
break;
// Clear the ss object.
ss.clear();
food.push_back(Nam);
serVings.push_back(servings);
pieces.push_back(piece);
amOunt.push_back(AmT);
ingredient.push_back(ingred);
}
inFile.close();
//create some iterators for the vectors.
vector< string >::iterator fIt = food.begin();
vector< int >::iterator sIt = serVings.begin();
vector< int >::iterator pIt = pieces.begin();
vector< string >::iterator aIt = amOunt.begin();
vector< string >::iterator iIt = ingredient.begin();
// Increament each vector iterator. This is a bad way though, read below.
for ( fIt; fIt != food.end(); ++fIt, ++sIt, ++pIt, ++aIt, ++iIt )
{
cout << *fIt << '\n';
cout << *sIt << '\n';
cout << *pIt << ' ' << *aIt << ' ' << *iIt << '\n';
}
return 0;
}
So, this program will read and store:
S'mores
2
4 squares graham crackers
The loop at the end it bad, because when you read in more ingredients, the next two lines;
1 bar milk chocolate
2 large marshmallows
You will have to some how keep a track of how many 'lines' of ingredients there are. You will also have to make a loop for each of the vectors, because sizes will vary and outputting them in the same loop will cause a violation error( Reading out of bounds of the vector ).