Tags:
create new tag
view all tags

Baseball player program

Player.h
// Class Definition: Player
// Version 1
// This class defines an object to hold information about 
// baseball player for use in a player database.
//--------------------------------------------------------
#include <iostream>
using namespace std;

class Player {
	string m_firstName;  // player's first name
	string m_lastName;   // player's last name
	string m_position;   // player's primary position
	double m_battingAverage;	// batting average

public:
	// Default Constructor
	Player();
	// copies data into the object with some simple formatting and
	// data checking
	Player(string, string, string, double);

	// define methods to read and write simple versions of player data
	// to/from streams
	void Read(istream&);
	void Write(ostream&);

	// define get/sets as needed
	double getBattingAverage();
	string getFirstName();
	string getLastName();
	string getFullName();
	string getPosition();
};


 
Player.cpp
// Class Implementation: Player
// Implementation of the methods for a player object
// A baseball player has a name, and some simple statistics
// Default constructor and initializer functions are provided
// as well as simple i/o and gets as needed to supply values
// from the object.
//-------------------------------------------------------------
#include <iostream>
#include <string>
#include <iomanip>
#include "Player.h"
using namespace std;

// Default constructor - set player to predefined values
Player::Player() {
	m_firstName = "";
	m_lastName = "";
	m_position = "";
	m_battingAverage = 0;
}

// copies data into the object with some simple formatting and
// data checking
Player::Player(string first, string last, string pos, double avg)
{
	m_firstName = first;
	m_lastName = last;
	m_position = pos;
	if (avg < 0) avg = -avg;  // at least try to correct
	m_battingAverage = avg;
}

// define methods to read and write simple versions of player data
// to/from streams

// Read assumes the player's data is in the input stream in the format:
// firstname lastname position average with only spaces between the data
// no other separator characters are used.  This will not work if a player's 
// name has embedded spaces!
void Player::Read(istream &input) {
	input >> m_firstName;
	input >> m_lastName;
	input >> m_position;
	input >> m_battingAverage;
}

// Write the Player data to an output stream with simple formatting
void Player::Write(ostream &out) {
	out << m_lastName << ", " << m_firstName << ": " << m_position;
	out << fixed;
	out << setprecision(3);
	out << " (" << m_battingAverage << ") ";
}

// define get/sets as needed
double Player::getBattingAverage() { return m_battingAverage;  }
string Player::getFirstName() { return m_firstName; }
string Player::getLastName() {  return m_lastName; }
string Player::getFullName() {  return  m_firstName + " " + m_lastName; }
string Player::getPosition() { return m_position; }
 
main.cpp
#include <iostream>
#include <vector>
#include "Player.h"
using namespace std;

int main(void) {

    const int MAXPLAYERS = 50;
    vector<Player> playerList; // array to store player objects
    Player currentPlayer; // current player being retrieved 
    int playerCount; // count players as they are retrieved
    string first, last, position;
    float batAverage;
    int i; // loop counter

    // file opened successfully 
    playerCount = 0;
    cout << "Enter a player first name, last name, position, and batting average, with a first name of END when done: ";
    cin >> first >> last >> position >> batAverage;
    while (first != "END" && playerCount < MAXPLAYERS) { // as long as there are lines of data to be read in
        currentPlayer = Player(first, last, position, batAverage);
        cout << "New Player: ";
        currentPlayer.Write(cout);
        cout << endl;
        // store in list
        playerList.push_back(currentPlayer);
        playerCount++; // count the player
        cout << "Enter a player first name, last name, position, and batting average, with a first name of END when done: ";
        cin >> first >> last >> position >> batAverage;
    }

    cout << "There are " << playerCount << " players in the program" << endl;
    for (i = 0; i < playerCount; i++) {
        playerList[i].Write(cout);
        cout << endl;
    }
    return 0;
}

 

Files

Simple File Input/Output

//DISPLAY 6.1 Simple File Input/Output
//Reads three numbers from the file infile.dat, sums the numbers,
//and writes the sum to the file outfile.dat.
//(A better version of this program will be given in Display 6.2.)
#include <fstream>

int main( )
{
    using namespace std;
    ifstream in_stream;
    ofstream out_stream;

    in_stream.open("infile.dat");
    out_stream.open("outfile.dat");

    int first, second, third;
    in_stream >> first >> second >> third;
    out_stream << "The sum of the first 3\n"
               << "numbers in infile.dat\n"
               << "is " << (first + second + third)
               << endl;

    in_stream.close( );
    out_stream.close( );

    return 0;
}
 

File I/O with Checks on open

//DISPLAY 6.2 File I/O with Checks on open
//Reads three numbers from the file infile.dat, sums the numbers,
//and writes the sum to the file outfile.dat. 
#include <fstream>
#include <iostream>
#include <cstdlib>

int main( )
{
    using namespace std;
    ifstream in_stream;
    ofstream out_stream;

    in_stream.open("infile.dat");
    if (in_stream.fail( ))
    {
        cout << "Input file opening failed.\n";
        exit(1);
    }

    out_stream.open("outfile.dat");
    if (out_stream.fail( ))
    {
        cout << "Output file opening failed.\n";
        exit(1);
    }

    int first, second, third;
    in_stream >> first >> second >> third;
    out_stream << "The sum of the first 3\n"
               << "numbers in infile.dat\n"
               << "is " << (first + second + third)
               << endl;

    in_stream.close( );
    out_stream.close( );

    return 0;
}
 

Appending to a File

//DISPLAY 6.3 Appending to a File
//Appends data to the end of the file data.txt.
#include <fstream>
#include <iostream>

int main( )
{
    using namespace std;

    cout << "Opening data.txt for appending.\n";
    ofstream fout;
    fout.open("data.txt", ios::app);
    if (fout.fail( ))
    {
        cout << "Input file opening failed.\n";
        exit(1);
    }

    fout << "5 6 pick up sticks.\n"
         << "7 8 ain't C++ great!\n";

    fout.close( );
    cout << "End of appending to file.\n";
 
   return 0;
}


 

Inputting a File Name

//DISPLAY 6.4 Inputting a File Name
//Reads three numbers from the file specified by the user, sums the numbers,
//and writes the sum to another file specified by the user. 
#include <fstream>
#include <iostream>
#include <cstdlib>

int main( )
{
    using namespace std;
    char in_file_name[16], out_file_name[16];
    ifstream in_stream;
    ofstream out_stream;

    cout << "I will sum three numbers taken from an input\n"
         << "file and write the sum to an output file.\n";
    cout << "Enter the input file name (maximum of 15 characters):\n";
    cin >> in_file_name;
    cout << "Enter the output file name (maximum of 15 characters):\n";
    cin >> out_file_name;
    cout << "I will read numbers from the file "
         << in_file_name << " and\n"
         << "place the sum in the file "
         << out_file_name << endl;

    in_stream.open(in_file_name);
    if (in_stream.fail( ))
    {
        cout << "Input file opening failed.\n";
        exit(1);
    }

    out_stream.open(out_file_name);
    if (out_stream.fail( ))
    {
        cout << "Output file opening failed.\n";
        exit(1);
    }
    int first, second, third;
    in_stream >> first >> second >> third;
    out_stream << "The sum of the first 3\n"
               << "numbers in " << in_file_name << endl
               << "is " << (first + second + third)
               << endl;
    in_stream.close( );
    out_stream.close( );

    cout << "End of Program.\n";
    return 0;
}


 

Formatting Output

//DISPLAY 6.6 Formatting Output 
//Illustrates output formatting instructions.
//Reads all the numbers in the file rawdata.dat and writes the numbers
//to the screen and to the file neat.dat in a neatly formatted way.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
using namespace std;

void make_neat(ifstream& messy_file, ofstream& neat_file,
             int number_after_decimalpoint, int field_width);
//Precondition: The streams messy_file and neat_file have been connected
//to files using the function open.
//Postcondition: The numbers in the file connected to messy_file have been
//written to the screen and to the file connected to the stream neat_file. 
//The numbers are written one per line, in fixed-point notation (that is, not in 
//e-notation), with number_after_decimalpoint digits after the decimal point; 
//each number is preceded by a plus or minus sign and each number is in a field 
//of width field_width. (This function does not close the file.)

int main( )
{
    ifstream fin;
    ofstream fout;

    fin.open("rawdata.dat");
    if (fin.fail( ))
    {
        cout << "Input file opening failed.\n";
        exit(1);
    }

    fout.open("neat.dat");
    if (fout.fail( ))
    {
        cout << "Output file opening failed.\n";
        exit(1);
    }
 
    make_neat(fin, fout, 5, 12);

    fin.close( );
    fout.close( );

    cout << "End of program.\n";
    return 0;
}
//Uses iostream, fstream, and iomanip:
void make_neat(ifstream& messy_file, ofstream& neat_file,
              int number_after_decimalpoint, int field_width)
{
    neat_file.setf(ios::fixed);
    neat_file.setf(ios::showpoint);
    neat_file.setf(ios::showpos);
    neat_file.precision(number_after_decimalpoint);
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.setf(ios::showpos);
    cout.precision(number_after_decimalpoint);

    double next;
    while (messy_file >> next)
    {
        cout << setw(field_width) << next << endl;
        neat_file << setw(field_width) << next << endl;
    }
}


 

Checking Input

//DISPLAY 6.7 Checking Input
//Program to demonstrate the functions new_line and get_input.
#include <iostream>
using namespace std;

void new_line( );
//Discards all the input remaining on the current input line.
//Also discards the '\n' at the end of the line.
//This version works only for input from the keyboard.

void get_int(int& number);
//Postcondition: The variable number has been
//given a value that the user approves of.


int main( )
{
    int n;

    get_int(n);
    cout << "Final value read in = " << n << endl
         << "End of demonstration.\n";
    return 0;
}


//Uses iostream:
void new_line( )
{
    char symbol;
    do
    {
        cin.get(symbol);
    } while (symbol != '\n');
}
//Uses iostream:
void get_int(int& number)
{
    char ans;
    do
    {
        cout << "Enter input number: ";
        cin >> number;
        cout << "You entered " << number
             << " Is that correct? (yes/no): ";
        cin >> ans;
        new_line( );
    } while ((ans != 'Y') && (ans != 'y'));
}

 

Editing a File of Text

//DISPLAY 6.8 Editing a File of Text 
//Program to create a file called cplusad.dat that is identical to the file
//cad.dat, except that all occurrences of 'C' are replaced by "C++".
//Assumes that the uppercase letter 'C' does not occur in cad.dat except
//as the name of the C programming language.

#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;

void add_plus_plus(ifstream& in_stream, ofstream& out_stream);
//Precondition: in_stream has been connected to an input file with open.
//out_stream has been connected to an output file with open.
//Postcondition: The contents of the file connected to in_stream have been
//copied into the file connected to out_stream, but with each 'C' replaced
//by "C++". (The files are not closed by this function.)

int main( )
{
    ifstream fin;
    ofstream fout;

    cout << "Begin editing files.\n";

    fin.open("cad.dat");
    if (fin.fail( ))
    {
        cout << "Input file opening failed.\n";
        exit(1);
    }

    fout.open("cplusad.dat");
    if (fout.fail( ))
    {
        cout << "Output file opening failed.\n";
        exit(1);
    }

    add_plus_plus(fin, fout);
    fin.close( );
    fout.close( );

    cout << "End of editing files.\n";
    return 0;
}

void add_plus_plus(ifstream& in_stream, ofstream& out_stream)
{
    char next;
    in_stream.get(next);
    while (! in_stream.eof( ))
    {
        if (next == 'C')
            out_stream << "C++";
        else
            out_stream << next;

        in_stream.get(next);
    }
}

 

File Example reverse lines

#include <fstream>
#include <iostream>
#include <cstdlib>
#include <vector>

int main( )
{
    using namespace std;
    ifstream in_stream;
    ofstream out_stream;

    in_stream.open("infile.dat");
    if (in_stream.fail( ))
    {
        cout << "Input file opening failed.\n";
        exit(1);
    }

    out_stream.open("outfile.dat");
    if (out_stream.fail( ))
    {
        cout << "Output file opening failed.\n";
        exit(1);
    }

    vector<string> strings;
    string s;
    getline(in_stream,s);
    while (!in_stream.eof()) {
        strings.push_back(s);
        getline(in_stream,s);
    }

    for (int k = strings.size()-1 ; k >= 0 ; k-- ) {
        out_stream << strings.at(k) << endl;
    }

    in_stream.close( );
    out_stream.close( );

    return 0;
}
 

Topic attachments
I Attachment History Action Size Date Who Comment
Unknown file formatdat cad.dat r1 manage 0.1 K 2016-11-15 - 11:55 JimSkon  
Texttxt data.txt r1 manage 0.1 K 2016-11-15 - 11:55 JimSkon  
Unknown file formatdat infile.dat r1 manage 0.1 K 2016-11-15 - 11:55 JimSkon  
Unknown file formatdat numbers.dat r1 manage 0.1 K 2016-11-15 - 11:55 JimSkon  
Unknown file formatdat rawdata.dat r1 manage 0.1 K 2016-11-15 - 11:55 JimSkon  
Edit | Attach | Watch | Print version | History: r5 < r4 < r3 < r2 < r1 | Backlinks | Raw View | Raw edit | More topic actions
Topic revision: r5 - 2017-04-13 - JimSkon
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2018 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback