Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nelsonlaquet
Created May 7, 2012 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nelsonlaquet/2631394 to your computer and use it in GitHub Desktop.
Save nelsonlaquet/2631394 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
struct Product
{
string Name;
string Notes;
double Price;
};
void PrintProduct(Product product)
{
cout << "Name: " << product.Name << "\n";
cout << "Price: " << product.Price << "\n";
cout << "Notes: " << product.Notes << "\n";
}
Product GetProductFromInput()
{
Product temp;
cout << "Enter name: ";
getline(cin, temp.Name); // << use this
cout << "Enter Price: ";
cin >> temp.Price;
cin.ignore();
cout << "Enter Notes: ";
getline(cin, temp.Notes); // << use this
return temp;
}
int main()
{
vector<Product> products;
Product p1 = {"Product 1", "Notes", 23};
Product p2 = {"Product 2", "Notes", 321};
Product p3 = {"Product 3", "Notes", 423};
Product p4 = {"Product 4", "Notes", 423423};
products.push_back(p1);
products.push_back(p2);
products.push_back(p3);
products.push_back(p4);
// SAVE products to products.txt
ofstream fout;
fout.open("products.txt");
for (unsigned int i = 0; i < products.size(); i++)
{
fout << products[i].Name << "\n" << products[i].Price << "\n" << products[i].Notes << "\n";
}
fout.close();
// LOAD file back in and print it
vector<Product> products2;
ifstream fin;
fin.open("products.txt");
while (!fin.eof())
{
Product product;
getline(fin, product.Name);
fin >> product.Price;
fin.ignore();
getline(fin, product.Notes);
products2.push_back(product);
}
fin.close();
cout << "PRODUCTS READ FROM FILE\n";
for (unsigned int i = 0; i < products2.size(); i++)
{
cout << "------------------ Product " << (i + 1) << " --------------------\n";
PrintProduct(products2[i]);
cout << "\n";
}
cin.ignore();
cin.get();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment