Intro to C++ - Part 3

OK, I have been slacking on this series. No Justice, thats a *BAD* Justice!. I have a coldfusion product going into alpha this week after more than a year of development, so what can I say =) Now on to more C++ goodness!


So lets talk about a few things that we went over this past week in class. We went over reading from and writing data to a file, which really isn't that hard. You need to be sure an #include <fstream> at the top of your code, to enable the ifstream (input) and ofstream (output) objects. Note here, you have to have one object to read, and one object to write. With my limited knowlege of why / how this is, I would think that a read could be a less invasive lock on the file, while a write would have to have a total lock on the file while changes were being written. I always try and comment code, and personally I think code speaks much louder than any words I type, so check out a program that I was working up while in class listening to lecture and watching examples on the board.

// week3InClass.cpp
//

#include <span class='cc_value'>"stdafx.h"</span>
#include <iostream>
#include <string><span class='cc_comment'> // adds the string data type</span>#include <fstream><span class='cc_comment'> // read and write to files</span>
using namespace std;

int main()
{
   int age = 0;
   string name = <span class='cc_value'>"Anonymous"</span>;
   string theFileContent = <span class='cc_value'>"File unable to be opened"</span>;

   bool wasFound = false;<span class='cc_comment'> // boolean data type</span>
   cout << endl << <span class='cc_value'>"Please enter your name:> "</span>;
<span class='cc_comment'>   // cin >> name;</span>
<span class='cc_comment'>   // Ignore X characters from the user input, basically ignores the 1st character. Why? just as an exercise on how!</span>   cin.ignore(1);
   
<span class='cc_comment'>   // Retrieve the next line of input from the cin object (console in, basically anything the user typed in), and stick it into the variable name</span>   getline(cin, name);

   cout << <span class='cc_value'>"Please enter your age:> "</span>;
   cin >> age;

   cout << endl << <span class='cc_value'>"Hello "</span> << name << <span class='cc_value'>", the age you entered was: "</span> << age << endl;

<span class='cc_comment'>   // Read from a file and do something</span>   ifstream inFile;<span class='cc_comment'> // input file stream object</span>   ofstream outFile<span class='cc_comment'>;// output file stream object</span>
   inFile.open(<span class='cc_value'>"c:\\boot.ini"</span>);<span class='cc_comment'> // open up the specified file</span>
<span class='cc_comment'>   // Check if the file opened up ok?</span>   if( inFile.is_open() ) {
      cout << <span class='cc_value'>"reading the file..."</span> << endl;
      inFile >> theFileContent;<span class='cc_comment'> // Go and get data from the file up to the 1st space</span>   }
   else {
      cout << <span class='cc_value'>"Failed to read the file, oh crap!"</span> << endl << endl;
      exit(-1);<span class='cc_comment'> // Bail out of the file and scream your head off Exiting with code -1 says 'something messed up here george'!</span>   }

<span class='cc_comment'>   // comparison operators</span>   if (theFileContent != <span class='cc_value'>"File unable to be opened"</span>) {
      cout << <span class='cc_value'>"OK, I managed to read the file, gonna do something cool now:"</span> << endl;
   }
   
<span class='cc_comment'>   // check it out, false and 0 are the same, as well as true and 1, just for giggles</span>   if (false == 0) {
      cout << <span class='cc_value'>"They are the same, false is the same as 0!"</span> << endl;
   }
   else {
      cout << <span class='cc_value'>"false and 0 are not the same, sorry bout your luck"</span> << endl;
   }
   
   cout << <span class='cc_value'>"The data I read from your file was: "</span> << theFileContent << endl;<span class='cc_comment'> // output the stuff we just read from the file</span>   
<span class='cc_comment'>   // Add together logical operators</span>   <span class='cc_comment'>/*
      && = AND
      || = OR
      ! = NOT
   */
</span>

   inFile.close();<span class='cc_comment'> // ALWAYS close the damn file!@ Leaving it open is bad, mmmkay?</span>
<span class='cc_comment'>   // Now lets write to a file</span>   outFile.open(<span class='cc_value'>"c:\\test.txt"</span>, ios::app);<span class='cc_comment'> // ios:app tells the system to open in append mode, rather than overwriting. Leave that param out to overwrite whatever is there</span>   outFile << theFileContent << endl;<span class='cc_comment'> // output the line to this file</span>   outFile.close();<span class='cc_comment'> // close and save the file</span>   

   return 0;
}

The other thing I want to share here is an exercise that I was assigned where you had to accept a cost on an item, the markup %, and the tax%, then output what the final sale price of the item was. I took it a bit beyond, in that I used setw(number) to basically right-justify output inside of a space {number} characters wide. This required the include of <iomanip> in the header. This exercise here also illustrates the use of functions, and using static_cast to manipulate output and calculations. You may want to read the top comment first, which has the exercise question in its entirety. Try solving it yourself first, then come back here and see how I did it.

*Please Note - This is a homework example straight from the book, and I have included it here as a learning exercise. I am posting these after the due-date in my current class to ensure nobody just copies this work and uses it as their own for school, but future students may end up doing just that. Remember, you are only cheating yourself to not read through these comments and come up with your own twist or method of achieving this goal.

OK, enough disclaimer, here is 'da-code!'

<span class='cc_comment'>/*
   Exercise:   Chapter 2 Exercise 16
   Located:   4th edition book, page 109-110

   Author:      Chris Peterson
   Date:      9-13-2008
   Class Date:   Fall 2008, Wednesday evenings

   Assignment:
   To make a profit, a local store marks up
   the prices of its items by a certain percentage.
   Write a C++ program that reads the original price
   of the item sold, the percentage of the marked up
   price, and the sales tax rate. The program then
   outputs the original price of the item, the
   percentage of the mark up, the store’s selling
   price of the item, the sales tax rate, the sales
   tax, and the final price of the item (the final
   price of the item is the selling price plus sales
   tax)
*/
</span>

#include <span class='cc_value'>"stdafx.h"</span>
#include <iostream>
#include <iomanip>

using namespace std;
<span class='cc_comment'>
// function variables</span>
double calculatePercent(double value, double percent);
<span class='cc_comment'>
// input variables</span>
double in_originalPrice = 0, in_markupRate = 0, in_taxRate = 0;
<span class='cc_comment'>
// internal calculated variables</span>
double markupAmount = 0, itemSalePrice = 0, taxAmount = 0, finalPrice = 0;
<span class='cc_comment'>
// Main method fires auto-magically</span>
int main()
{
<span class='cc_comment'>   // cout - print a result out to the console</span>   cout << <span class='cc_value'>"This program will calculate the final sale price of\n"</span>
       << <span class='cc_value'>"an item by adding markup and tax to the base item cost.\n"</span>
       << <span class='cc_value'>"Please enter all percentage values as whole numbers\n"</span>
       << <span class='cc_value'>"(6% would simply be the number 6)"</span> << endl << endl;
   
   cout << <span class='cc_value'>"Please enter the dollar cost of the item (store paid cost) > "</span>;
   cin >> in_originalPrice;
   cout << endl;

   cout << <span class='cc_value'>"Please enter the markup percentage >"</span>;
   cin >> in_markupRate;
   cout << endl;

   cout << <span class='cc_value'>"Please enter the tax percentage rate >"</span>;
   cin >> in_taxRate;
   cout << endl;

<span class='cc_comment'>   // Perform the necessary calculations here</span>   markupAmount = static_cast<double>(
      calculatePercent(
            static_cast<double>(in_originalPrice),
            static_cast<double>(in_markupRate)
         )      
      );

   itemSalePrice = (in_originalPrice + markupAmount);

   taxAmount = static_cast<double>(
      calculatePercent(
            static_cast<double>(itemSalePrice),
            static_cast<double>(in_taxRate)
         )      
      );

   finalPrice = (itemSalePrice + taxAmount);

<span class='cc_comment'>   // Perform all output here now that we have things calculated</span>
   cout << <span class='cc_value'>"****************************************"</span> << endl;
   cout << setfill(' ') << fixed << showpoint << setprecision(2);
   cout << <span class='cc_value'>"Item Original Cost: "</span> << setw(20) << in_originalPrice << endl;
   cout << <span class='cc_value'>"Markup Rate: "</span> << setw(15) << <span class='cc_value'>"%"</span> << setw(5) << static_cast<int>(in_markupRate) << endl;
   cout << <span class='cc_value'>"Item Sell Price: "</span> << setw(20) << itemSalePrice << endl;
   cout << <span class='cc_value'>"Sales Tax Rate: "</span> << setw(15) << <span class='cc_value'>"%"</span> << setw(5) << static_cast<int>(in_taxRate) << endl;
   cout << <span class='cc_value'>"Sales Tax Amount: "</span> << setw(20) << taxAmount << endl;
   cout << <span class='cc_value'>"----------------------------------------"</span> << endl;
   cout << <span class='cc_value'>"Final Item Price: "</span> << setw(20) << finalPrice << endl << endl;

   return 0;
}

double calculatePercent(double value, double percent) {
   double result = 0;

   result = (value * (percent / 100));

   return result;
}
Digg StumbleUpon Facebook Technorati Fav newsvine reddit FARK Google Bookmarks
  1. kaldon

    #1 by kaldon - October 17, 2008 at 11:54 AM

    Hi,
    How can I write this using the Basic Elements of java.
    here my try:
    import java.util.*;
    public class Ex13
    {
    static Scanner console=new Scanner(System.in);
    public static void main(String[]args)
    {

    double originalprice,markup,salesTax,sellprice;

    originalprice=console.nextDouble();

    markup=console.nextDouble();
    salesTax=console.nextDouble();
    sellprice=originalprice*(1+markup)*(1+salesTax);


    System.out.println("The original price of the item is: "+originalprice);
    System.out.println("The mark up percentage is: "+markup);
    System.out.println("The selling price of the item is: "+sellprice);

    }
    }

    & can you please tell me if my answer for this exercise is correct:
    A milk carton can hold 3.78 liters of milk.Each morning,a dairy farm ships cartons of milk to a local grocery store.The cost of producing one liter of milk is $0.38, and the profit of each carton of milk is $0.27. write a program that dose the following:
    1, a. Prompts the user to enter the total amount of milk produced in the morning
    b.Output the number of milk cartons needed to hold milk (Round your answer to the nearest integer.)
    c. Output the cost of producing milk.
    d. Output the profit for producing milk.

    here my answer :$
    import java.util.*;
    public class Ex16
    {
    static Scanner console=new Scanner(System.in);
    public static void main(String[]args)
    {
    int amt;

    System.out.println("please enter the amount of milk");

    amt=console.nextInt();

    double numcartons,cost,profit;
    numcartons=amt/3.78;
    cost=amt*0.38;
    profit=numcartons*0.27;
    System.out.println("The number of cartons required is: "+numcartons);
    System.out.println("The cost of productions is: "+cost);
    System.out.println("The profit is: "+profit);

    }
    }

Comments are closed.