Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Declaring input file as private in class

Status
Not open for further replies.

tmcneil

Technical User
Nov 17, 2000
294
US
I'm not sure what I am doing wrong here, but my class will not compile. I have to declare my input file as private and then open in my destructor. I then have to close it in my destructor when I am done using it. Any ideas?

Code:
#ifndef NUM_H
#define NUM_H

#include <iostream>
#include <fstream>

class num_info
{
	public:                          
		int num;   // 1 field in array
}; //end class rand_info
#endif

//Make use of above class to declare an array of class rand_info

#ifndef NUM_FILE_H
#define NUM_FILE_H

#define MAX 10
class num_class
{
	 private:
         class num_info num_ary [MAX];    //an array to store 1 field of num_info
		 int count;                       //number of records stored in array
         int largest, smallest;           //largest and smallest number in file
         //int infile;
         int ifstream infile;             // internal name for input file

	 public:
		 num_class ();               //constructor
		 ~num_class (void);          //destructor
		 void read_ary (void);        //Reads data in the file and keeps track of number of data items read.
         void print_ary (char ch);
         //void lasm_ary (void);
         //void sort_ary (void);
         //void comp_frequency (void);
		 //void print_recs (char ch);  //print records in array

		 //void comp_grades (void);    //compute letter grades
		 //void alphabetize (void);    //alphabetize records by name

}; //end class
#endif
 
I don't think the word class should be in the line:

Code:
   class num_info num_ary[MAX];   //an array to store 1 field of num_info
   //  shoud be
   // num_info num_ary[MAX];     // an array to store 1 field of num_info

Any verbage on the reason it won't compile? What does the destructor() function look like?


HyperEngineer
If it ain't broke, it probably needs improvement.
 
Header file

Code:
// Numbers.h C++ source code for rand_class class specification

#ifndef NUM_H
#define NUM_H

#include <fstream>
#include <iostream>

class num_info
{
	public:                          
		int num;   // 1 field in array
}; //end class num_info
#endif

//Make use of above class to declare an array of class rand_info

#ifndef NUM_FILE_H
#define NUM_FILE_H

#define MAX 10
class num_class
{
	 private:
         ifstream infile;   //creates errors here on infile.
         num_info num_ary [MAX];    //an array to store 1 field of num_info
		 int count;                       //number of records stored in array
         int largest, smallest;           //largest and smallest number in file

	 public:
		 num_class ();               //constructor
		 ~num_class (void);          //destructor
		 void read_ary (void);        //Reads data in the file and keeps track of number of data items read.
         void print_ary (char ch);
         //void lasm_ary (void);
         //void sort_ary (void);
         //void comp_frequency (void);
		 //void print_recs (char ch);  //print records in array

		 //void comp_grades (void);    //compute letter grades
		 //void alphabetize (void);    //alphabetize records by name

}; //end class
#endif

Methods

Code:
// File: Numbers.cpp. C++ source code for num_class methods

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

#define DASHES "-----------------------------------------------------------"
#define SEPARATOR "--------------"
#define NAME "Todd McNeil"

#include "Numbers.h"

//*****************************************************************************
// This constructor instantiates count as 0, prints info and opens Randoms.txt
// for input.
//*****************************************************************************
num_class::num_class (void)
{
    count = 0;

    cout << DASHES;
	cout << "\n     Programmer Name: " << NAME;
	cout << "\n     Section: CSI 155/Section 875";
    cout << "\n     Lab/Project No.: Lab #4";
	cout << "\n     Date   : 03/17/2006\n";
	cout << DASHES << endl << endl << endl;

    //ifstream infile;  // internal name for input file
    infile.open ("Numbers.txt");
    //ifstream infile ("Numbers.txt");

    if (infile.fail())  //see if file opened successfully
    {
        cout << "File could not be opened for input\n";
	    exit (1);  // abort the program
    }

}// end constructor


//*****************************************************************************
// read_ary(): method Reads data in the file, Randoms.txt, into the array and
// keeps track of (count) the number of data items read. Also prints out header
// information to the screen.
//-----------------------------------------------------------------------------
void num_class::read_ary (void)
{
    int temp_num;

    count = 0;
    infile >> temp_num;  // read score in temporary location; prime read

    while (!infile.eof()) && count < 10)   //read no more than 500 numbers
    {   num_ary [count] = temp_num;        //store number read in array
        count++;
        // read next number in temporary location
        infile >> temp_num;  //next read just before end of while loop
    }
}//end read_ary

//***************************************************************************
// print_ary() method prints the numbers stored in the array 15 to a line.
// Print each number right justified in four columns.  Give an appropriate
// table heading such as Original List of Data Items.  Also print the total
// # of data items read from the file.  Number the columns and lines.
//***************************************************************************

void num_class::print_ary (char ch)
{
    switch (ch)
	{
	   case 'o':  cout << "\n\n\t\tOriginal List\n\n";
                  break;
 	
	   case 'a':  cout << "\n\n\n\t\tAlphabetized List\n\n";
                  break;
	} //end switch

	for (int i=0; i<count; i++)
		cout << setw(10)<< right << i+1 << ".     " 
             << setw (5) << num_ary [i].num << endl;

}  // end print_ary()

/*
//*****************************************************************************
// This method/function determines and prints out the winner after 500 tosses
//-----------------------------------------------------------------------------

void TossDie::tossWinner (int i, char oppName[20])
{
    cout << endl << endl;
    cout << "Total Number of Tosses = " << i-1 << "." << endl << endl;
    cout << endl << "Shooy-Mooy's Score     = " << smScore << "." << endl;
    cout << "Opponent" << "'s Score       = " << oppScore << "." << endl;
    cout << "Number of Draws        = " << draw << "." << endl;
    
    if (smScore > oppScore)
    {
        cout << endl << "The Grand Champion is -> Shooy-Mooy." << endl;
    }
    else if (smScore < oppScore)
    {
        cout << endl << "The Grand Champion is -> " << oppName << endl;
    }
    else
    {
        cout << endl << "The Grand Champion is -> It's a Draw!" << endl;
    }
}
*/
//*****************************************************************************
// This destructor gets executed upon exit from a function.  Closes input file.
//*****************************************************************************

 num_class::~num_class (void)
{
    infile.close ();

	char ch;
     
    cout << "\n******************Goodbye for Now*********************\n";
    cout << "\n\nPress any letter or digit key to exit: ";
    cin >> ch;
}// end destructor

main ()

Code:
#include <iostream>
#include <fstream>    // for file declaration/manipulation
#include <iomanip>
#include <string>

#include "Numbers.h"

using namespace std;

int main (void)
{
	class num_class num_recs;

	num_recs.read_ary ();

	num_recs.print_ary ('a');
	//stu_recs.print_recs ('o');

	//stu_recs.alphabetize( );
	//stu_recs.print_recs ('a');

	//system ("pause");
    return 0;
}
 
You didn't say what the errors are, but chances are you need to specify the std namespace for your ifstream.
 
Alternatively in main program move the using namespace std to before include "numbers.h
 
So, I've made some progress on my program. However I'm stuck on trying to find the frequency of data items in an array.

Instructions
Code:
A fifth method, comp_frequency, computes frequency of each random number generated.  Print the number and the corresponding frequency under appropriate column headings. Give an appropriate table heading.

There is more than one algorithm to find frequency of data items.  One of the algorithm is to sort the array first.  Store the first number in a variable new_num and start the frequency count at 1 for the first number (new_num) and then count using a while loop how many of the numbers in array have the same value equal to the new_num.  

As soon as you hit a number different than the new_num number in a sorted array, print out new_num and its frequency; re-initialize the frequency at 1 again and store the new/different number in the variable new_num.

For example, assume the data stored in the sorted array is as follows:
2  	2  	2  	4  	10  	10  	10  	10

Initialize new_num first element, which is two in this case.  Keep counting how many elements are equal to the new_num (which is 2); the frequency for 2 in this example is 3.  As soon as we hit a number different than the ones we were counting, print the number and the frequency and start frequency at 1 again for the new number (different number than the previous one which is 4 in this example) and count the number of times new value appears in the array.

Keep repeating the process.

You will need two loops.  Outside loop to traverse all elements in the array such as
     //initialize i to 0
     while ( i < count)   ? assuming there are count number of elements in the array.
          //initialize frequency to 1 and new_num ? sorted_array[0]

Second loop (another while loop? while (previous number (new_num) == next number in the array)) will be inside the first while loop; keep counting and incrementing i until you hit an element different than the one you were finding the frequency of.  In that case, print the number and its frequency; set frequency to 1 again and the previous number to the new number.   Here previous number and next number will be written in terms of array elements.  Make sure you check the value of i so it does not exceed count in any test.

I don't really understand what I am supposed to do since my professors explanation is more confusing that it is anything.

Todd
 
Here's the code, but I am getting an endless loop.

Code:
void num_class::comp_frequency (void)
{
    int new_num;
    //int count;
    int freq;

    //new_num = num_ary[0].num;  //store the first number in array

    int i = 0;
    while (i < count)   //assuming there are count number of elements in the array.
    {
        freq = 1;
        new_num ==  num_ary[0].num;
        while ((new_num) == num_ary[i].num)
        {
            freq++;
            i++;
        }
        cout << "\n\n\t\t\t\t\t\t\t\t  Page No. 3" ;
        cout << "\n\n\t\tFrequency Table for Random Number Generated\n\n";
        cout << "\t\t\t\tBy: " << NAME;
        cout << endl << endl << "\t\t\t\t" << SEPARATOR << endl;
    }
}  // end comp_frequency()

My table output has to look like this:

-------------------------------------------------------------------------------------------------
Line# Data Item Frequency
-------------------------------------------------------------------------------------------------
1. 11 27
2. 12 51
etc. etc. etc.
------------------------------------------------------------------------------------------------
 
xwb said:
Alternatively in main program move the using namespace std to before include "numbers.h"
Yes, you could do that, but you should never put using declarations before #include directives or in header files. If you have "C++ Coding Standards" by Herb Sutter & Andrei Alexandrescu you can read item 108 to find out more about why you shouldn't do that.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top