Help with classes and addition!

This is a discussion on Help with classes and addition! within the C++ Programming forums, part of the General Programming Boards category; Hi, I am currently trying to do an assignment where I read in from a file, three variables from each ...

  1. #1
    ^ Read Backwards^
    Join Date
    Sep 2005
    Location
    Earth
    Posts
    282

    Help with classes and addition!

    Hi,

    I am currently trying to do an assignment where I read in from a file, three variables from each line, add them together and then at the end basically add each column up.
    We have to use classes.

    Reading works, adding each line works, and writing all that to a file works.

    However, adding each individual column gets me some really crazy and crappy stuff.

    I have tried doing it with temp variables in my class, temp variables in my loop and out of my loop.
    I either get odd results like “-9.25596e+061” or, results that appear to have worked correct but completely bad math.


    Right now my code might look a little messy, because well I have tried 15 different things, and having to change stuff so much I did not want to waste the time of typing lots of nice comments and descriptive variable names. And right now my output it kinda messy, but it is pointless cleaning that up unless I can get it to add correct!

    Here is my code:

    Code:
    #include <iostream>
    #include <fstream>
    #include <cmath>
    #include <cstdlib>
    using namespace std;
    
    
    class SalesFigures
    {
    
    public:
    	SalesFigures(double jan, double feb, double march_);
    	SalesFigures();
    
    	void write_out();
    	void write_out_total();
    	void math(double in, double in2, double in3);
    
    
    
    private:
    	double january;
    	double febuary;
    	double march;
    	double jan_total;
    	double feb_total;
    	double march_total;
    };
    
    
    
    int main()
    {
    
    
    	double in_1,in_2,in_3;
    	SalesFigures one;
    
    //	double temp1, temp2, temp3;
    
    	ifstream in_stream;
    	in_stream.open("source.txt");
    	
    	
    
    
    	while (! in_stream.eof())
    	{
    
    	
    	in_stream >> in_1 >> in_2 >> in_3;
    
    
    	one =SalesFigures(in_1,in_2,in_3) ;
    
    	one.write_out();
    	
    	one.math(in_1,in_2,in_3);
    
    
    	
    
    	
    
    //	temp1 = in_1 + temp1; 
    //	temp2 = in_2 + temp2;
    //	temp3 = in_3 + temp3;
    
    
    		
    	
    	}
    
    
    
    	one.write_out_total();
    
    //	ofstream out_f;
    //	out_f.open("output.txt",ios::app);
    
    //	out_f << temp1 << " " << temp2 << " " << temp3;
    
    	in_stream.close();
    
    	system("pause");
    
    	
    
    
    	return 0;
    }
    
    
    
    
    
    
    
    SalesFigures::SalesFigures(double jan, double feb, double march_)
    {
    
    	january = jan;
    	febuary = feb;
    	march = march_;
    
    }
    
    
    
    SalesFigures::SalesFigures()
    {
    	january = 0;
    	febuary = 0;
    	march = 0;
    	jan_total = 0;
    	feb_total = 0;
    	march_total = 0;
    
    
    
    }
    
    
    void SalesFigures::write_out()
    {
    
    	ofstream out_f;
    	out_f.open("output.txt",ios::app);
    
    	out_f << january << " " << febuary  << " " << march << " " << january + febuary + march << endl ;
    
    	out_f.close();
    
    
    }
    
    void SalesFigures::math(double in, double in2, double in3)
    {
    
    	jan_total = (in + january);
    	feb_total = (in2 + febuary);
    	march_total = (in3 + march);
    
    }
    
    
    
    void SalesFigures::write_out_total()
    {
    
    	ofstream out_f;
    	out_f.open("output.txt",ios::app);
    
    	out_f << jan_total << " " << feb_total  << " " << march_total << " " << jan_total + feb_total + march_total << endl ;
    
    	out_f.close();
    }
    As you will see some things commeted out that I tried.

    The source file is currently hardcoded to source.txt, here is an example of it:
    Code:
    105.1 298.3 37998.4
    644.9 5654.8 6654.2
    65457.1 86465.1 96454.1
    Any help would be much appericated!

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,200
    Your problem is that you're not initialising some of the members of your class. Make sure that the thre argument constructor initialises the _total members.

    Similarly, in your main() functio, when you uncomment the temp variables, make sure you initialise those.

    Essentially, if you forget to initialise a variable, the value it gets can be junk. And when you add something to a junk value, you get another junk value.....

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,794
    I would overload the stream extraction (>>) and insertion (<<) operators for the class. You can then move all the file related code outside of the class itself (at least the output file), like it appears you tried to do, instead of relying on repeatedly opening and closing these files within the functions themselves.

    If you combine that with overloading the addition operator, you can get rid of the math and write and write_out_total member functions and make the class function better (more naturally) within the program. You should also be able to get rid of the jan_total, feb_total, and march_total member variables and instead rely on the addition operator to return a new SalesFigures object with its own january, february, and march values all properly initialized to indicate the totals you had been asked to calculate.

    Also, if your input file is ever going to have a variable number of entries, you'd probably want to consider using an STL container to store many SalesFigures objects (like a vector perhaps).

    You should also be checking that your files are opened before you attempt to read/write to them.

    Here is what I would suggest for your SalesFigures class along with the overloaded operators:
    Code:
    class SalesFigures
    {
        double january;
        double february;
        double march;
    public:
        // Our class constructor... uses defualt arguments and initializer list
        SalesFigures(double jan = 0.0, double feb = 0.0, double mar = 0.0 ) : january(jan),
                                                                              february(feb),
                                                                              march(mar)
        {
        }
    
        // Overloaded operators
        friend SalesFigures& operator+(const SalesFigures&,const SalesFigures&);
        friend ostream& operator<<(ostream&,const SalesFigures&);
        friend istream& operator>>(istream&,SalesFigures&);
    };
    
    SalesFigures& operator+(const SalesFigures& lhs,const SalesFigures& rhs)
    {
        return SalesFigures(lhs.january+rhs.january,
                            lhs.february+rhs.february,
                            lhs.march+rhs.march);
    }
    
    ostream& operator<<(ostream& os,const SalesFigures& sales)
    {
        // Default precision for doubles is 6 digits which means (depending on the
        // values involved), that your results output may appear to be truncated/rounded.
        // You will have to decide how many digits of precision you need and how
        // best to deal with that.
        os.precision(10);
        return os << sales.january << ' '
                  << sales.february << ' '
                  << sales.march << ' '
                  << sales.january + sales.february + sales.march
                  << endl;
    }
    
    istream& operator>>(istream& is,SalesFigures& sales)
    {
        return is >> sales.january >> sales.february >> sales.march;
    }
    Your main function then just needs to open the input and output files (only once) and check that they are both open (error checking). If you are using a vector<SalesFigures> container to store all your data (recommended), you can then use the overloaded stream insertion operator in a loop to load the data into a temporary SalesFigures object and then push it onto the vector (I'd use the copy function in the algorithm header to load the whole file into the vector, it's just one line of code). Once that is done, you could sum the columns using the overloaded addition operator storing the results into a seperate "totals" SalesFigures object using a loop (here I'd personally use the accumulate function from the numeric header to do this, again it's just one line of code). Finally, you just need to output all the data from the vector to the output file, you could use a loop if needed (again, I'd use the handy copy function to do this), followed by one more output line to output the "totals" object to the file.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    ^ Read Backwards^
    Join Date
    Sep 2005
    Location
    Earth
    Posts
    282

    Re:

    Grumpy:

    Thank you for your input. Initializing the temp variables to zero makes it work properly with that method.

    That is not the method of the assignment though, I am to use constructors (as you see I tried); I was just trying that because I could not get it to work the other way.

    However, I still can not get the constructor method to work.

    Before the while loop, I declare the class type SalesFigures of ‘one’. Should it not call the default constructor then? The default constrictor sets everything to zero including my _totals.

    Then in the loop I call the constructor with three types of double, so it should only modify the three non _total variables.

    But for some reason, when I then and go output the _total variables, the values are not correct. As in the addition is wrong?


    hk_mp5kpdw:

    Pretty much everything you said we just covered today in class. However, the assignment was assigned Tuesday, and people today asked if we could use this for the assignment and she said no, only what you had learned up until the assignment was made. She said she has a very specific reason and we will use the “better” method in the next project once we cover friend functions a little more.

    How I am doing it is not all we learned, and I will not have every function open and close the files, but I tried breaking everything down because I can not get my addition to work properly!

    But thanks for the input!

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    6,200
    Quote Originally Posted by Enahs
    Thank you for your input. Initializing the temp variables to zero makes it work properly with that method.

    That is not the method of the assignment though, I am to use constructors (as you see I tried); I was just trying that because I could not get it to work the other way.

    However, I still can not get the constructor method to work.

    Before the while loop, I declare the class type SalesFigures of ‘one’. Should it not call the default constructor then? The default constrictor sets everything to zero including my _totals.
    The problem actually occurs because of the line;
    Code:
    one =SalesFigures(in_1,in_2,in_3) ;
    which creates a temporary SalesFigures object using the three argument constructor (which will have three uninitialised members) and then assigns "one" so it is equivalent to that object. Hence "one" winds up with three members that contain junk.

    Which is why I say you need to initialise all of the members in the three argument constructor, as well as in the default constructor.

    Quote Originally Posted by Enahs
    Then in the loop I call the constructor with three types of double, so it should only modify the three non _total variables.

    But for some reason, when I then and go output the _total variables, the values are not correct. As in the addition is wrong?
    The offending line I described above is in the loop: you are reassigning the object.

    The addition works find. When you add junk to anything you get junk.

  6. #6
    ^ Read Backwards^
    Join Date
    Sep 2005
    Location
    Earth
    Posts
    282
    The addition works find. When you add junk to anything you get junk.
    I started over from scratch, with what you all said in mind.

    It is very neat, and damn nice code now I might say. It is odd, but I now have a huge feeling of overwhelming satisfaction.

    Thanks again man!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I need the code of few programs in c++.plzzzzz help...plzzz
    By NAVINKR20 in forum C++ Programming
    Replies: 1
    Last Post: 05-08-2009, 09:13 AM
  2. A simple program using ARRAYS, STRUCTS, and CLASSES
    By CStudentHelp in forum C++ Programming
    Replies: 8
    Last Post: 04-17-2008, 09:57 PM
  3. Classes
    By yodoblec in forum C++ Programming
    Replies: 3
    Last Post: 06-29-2003, 01:07 PM
  4. From the standard
    By Unregistered in forum C# Programming
    Replies: 23
    Last Post: 02-20-2002, 02:03 PM
  5. Exporting Object Hierarchies from a DLL
    By andy668 in forum C++ Programming
    Replies: 0
    Last Post: 10-20-2001, 01:26 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21