View Single Post
  #3 (permalink)  
Old May 15th, 2016, 03:43 PM
phztfte1 phztfte1 is offline
Authorized User
Points: 384, Level: 6
Points: 384, Level: 6 Points: 384, Level: 6 Points: 384, Level: 6
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Nov 2014
Posts: 91
Thanks: 2
Thanked 1 Time in 1 Post
Default Chapter 15 Demystifying C++ I/O

Sorry Marc, but I was not able to put the pieces together. I need to see an explicit example.
I modified the void output() method to write to a file. It is shown in the code as boldfaced.
Now, how do you read the Muffin.txt file?
Code:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

class Muffin 
{
    public:
        string    getDescription() const;
        void      setDescription(const string& inDesc);
        int       getSize() const;
        void      setSize(int inSize);
        bool      getHasChocolateChips() const;
        void      setHasChocolateChips(bool inChips);

        void      output();
    protected:
        string    mDesc;
        int       mSize;
        bool      mHasChocolateChips;
};

string Muffin::getDescription() const { return mDesc; }
void Muffin::setDescription(const string& inDesc) { mDesc = inDesc; }
int Muffin::getSize() const { return mSize; }
void Muffin::setSize(int inSize) { mSize = inSize; }
bool Muffin::getHasChocolateChips() const { return mHasChocolateChips; }
void Muffin::setHasChocolateChips(bool inChips) { mHasChocolateChips = inChips; }

void Muffin::output()
{
	ofstream outFile("Muffin.txt", ios::out | ios::app);
        if(!outFile.is_open()) {
             cerr << "File could not open!";
             return;
        }
	outFile << getDescription().c_str() << getSize() << getHasChocolateChips() << '\n';
	outFile.clear();
	outFile.close();
}

Muffin createMuffin(istringstream& inStream);

int main()
{
  cout << "First, let's create a muffin in code and output it." << endl;

  Muffin m;
  m.setDescription("Giant_Blueberry_Muffin");
  m.setSize(42);
  m.setHasChocolateChips(false);

  m.output();

  cout << "Now we'll create a muffin from a string stream" << endl;

	istringstream instream("My_Muffin 2 true");
  Muffin m2 = createMuffin(instream);

  m2.output();

  return 0;
}

Muffin createMuffin(istringstream& inStream)
{
  Muffin muffin;
  // Assume data is properly formatted:
  // Description size chips

  string description;
  int size;
  bool hasChips;

  // Read all three values. Note that chips is represented
  // by the strings "true" and "false"
  inStream >> description >> size >> boolalpha >> hasChips;
  muffin.setSize(size);
  muffin.setDescription(description);
  muffin.setHasChocolateChips(hasChips);

  return muffin;
}

The output in the Muffin.txt file was as follows:
Code:
Giant_Blueberry_Muffin420
My_Muffin21

Last edited by phztfte1; May 15th, 2016 at 06:48 PM.. Reason: Correct editorial error and added check if file opened.