If I wanted to put each of the products I have in the below code into a .txt file how would I input that into the vectors? Pretty lost and confusing actually. I want to have a function that will input data into the vectors, and than display the menu.
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
usingnamespace std;
struct Product
{
int itemID;
string itemName;
int pOrdered;
float manufPrice; // These are floats
float sellingPrice; // Floats
string heading;
};
void menu(); // Make a function for your menu.
void readInData(std::ifstream&, std::vector<Product>&); // Function for read in from files.
int main()
{
std::ifstream fin("Filename.txt"); // Load the file
std::vector<Product> productList; // Initialize the vector.
readInData(fin, productList); // Call the function
}
void readInData(std::ifstream& fin, std::vector<Product>& pL) // Pass BOTH by REFERENCE
{
Product tmp; // temporary storage for our read in values.
while (!fin.eof()) // While we haven't seen the end of the file marker
{
// Filename.txt should be in this order for this to work
// Read in the numbers first
fin >> tmp.itemID >> tmp.pOrdered >> tmp.manufPrice
>> tmp.sellingPrice;
// Read in the item's name using getline()
std::getline(fin, tmp.itemName);
// Put in vector.
pL.push_back(tmp);
}
}
This is the order REQUIRED for the function I define above.
If you try to use fin>> with the itemName and it has a space in the input it will only take the first part before the space.
std::getline avoids this.
Otherwise you'll get a nasty error trying to place strings into integers.