13 - Streams Example Code

From Maryville College CS Wiki
Jump to: navigation, search


iofun.cpp

File: iofun.cpp

#include <iostream>
#include <string>
#include <limits>
#include "iofun.h"

using namespace std;

// Prompt for an integer.  Force the user to give us a number
// or end the file.
int prompt_int(string prompt)
{
    int n;  //number

    //loop until we get a valid input
    for(;;) {
        //try to get the number
        cout << prompt;
        cin >> n;

        //if we succeed, or the input ends, return
        if(cin or cin.eof()) {
            return n;
        }

        //something went wrong
        cout << "Invalid entry. Please Try Again" << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    } 
}


// Prompt the user for an integer within a given range
// only return valid output, or return on eof
int prompt_int_range(string prompt, int min, int max) 
{
    int n;  //number we read

    //loop until we get a valid input
    for(;;) {
        n = prompt_int(prompt);

        //return valid integers
        if(n >= min and n <= max) {
            return n;
        }

        //return on eof
        if(cin.eof()) {
            return n;
        }

        //print an error message
        cout << "Entry out of range.  Please try again." << endl;
    }
}


ifstream_demo.cpp

File: ifstream_demo.cpp

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream file;

    //open our own source code
    file.open("ifstream_demo.cpp");
    if(not file) {
        cout << "Failed to open file" << endl;
        return -1;
    }

    //read the contents of the file, and write them to the screen
    while(not file.eof()) {
        //read a character from the file
        char c = file.get();
    
        cout << c;
    }

    //cleanup 
    file.close();
}


average.cpp

File: average.cpp

//Compute an average of all numbers entered
#include <iostream>
#include <limits>
#include "iofun.h"

using namespace std;


int main()
{
    double sum = 0.0;  //the sum of all the numbers
    int count=0;       //the number of numbers

    do {
        //get a number
        int n = prompt_int("Enter a number (Ctrl+d to exit): ");
    
        if(not cin.eof()) {
            //add to our sum, if there was a number
            sum += n;
            count++;
        }
    } while(not cin.eof());

    //print the average
    cout << endl <<endl <<  "The average is: " << sum / count << endl;
}


write_holdings.cpp

File: write_holdings.cpp

// Write stock holdings to a file called STOCKS.DAT
// Format:
//    <symbol> <qty> <price> \endl
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ofstream file;

    //open STOCKS.DAT
    file.open("STOCKS.DAT");
    if(not file) {
        cout << "Could not open holdings file" << endl;
        return -1;
    }

    //write some holdings
    file << "IBM" << " " << 100 << " " << 250 << endl
         << "MSC" << " " << 10 << " " << 35 << endl;

    //cleanup 
    file.close();
}


stock.cpp

File: stock.cpp

#include <iostream>
#include <sstream>
#include "iofun.h"

using namespace std;

int main()
{
    ostringstream menu_stream;  //for writing the menu
    string menu;                //menu string

    //create the menu
    menu_stream << "\tStock Portfolio Management System" << endl
                << "\t\tPlease Make a Selection" << endl
                << "\t1 -- Buy a Stock" << endl
                << "\t2 -- Sell a Stock" << endl
                << "\t3 -- Report Current Holdings" << endl
                << "\t4 -- Report Gains and Losses" << endl
                << "\t5 -- Remove a Current Holding" << endl
                << "\t6 -- Done! (quit) " << endl
                << endl
                << "\tChoice? ";
    menu = menu_stream.str();

    int choice = prompt_int_range(menu, 1, 6);

    cout << "You chose " << choice << endl;

}


read_holdings.cpp

File: read_holdings.cpp

// Write stock holdings to a file called STOCKS.DAT
// Format:
//    <symbol> <qty> <price> \endl
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

int main()
{
    ifstream file;

    //open the file for reading
    file.open("STOCKS.DAT");
    if(not file) {
        cout << "Could not open file for reading." << endl;
        return -1;
    }

    //read the entire file
    while(not file.eof()) {
        //variables for the fields
        string symbol;
        int qty; 
        double price;

        //read in the variables
        file >> symbol >> qty >> price;
        if(file.eof()) {
            //if we reach the end of the file, skip the rest of the loop
            continue;
        }

        //print out the variables
        cout << setw(3) << symbol << setw(10) << qty << setw(10) << price << endl;
    }

    //cleanup
    file.close();
}