BTP200

Input and Output Refinements

Summary

Stream Objects

Input Objects

Output Objects

Stream Objects

Overview

A stream is a sequence of items with no clear boundary

In C++, a stream is a sequence of bytes

Input streams receive bytes from a source and store it in the application memory

Output streams forward bytes from the application memory into a destination

Libraries

The iostream library defines a number of objects and functions to deal with command line inputs and outputs

The fstream library defines a number of objects and functions to deal with reading/writing from/to files

IOSTREAM

IOStream Objects

std::cin is an object of the class istream

std::cout is an object of the class ostream

Both initiated when compiling the iostream library

std::cin

std::cin is frequently used with the overloaded extraction operator: >> (which can be chained)

std::cin >> var takes a user input and stores in the variable var

The application will try to match the type of the input to the type of var

std::cin uses whitespaces as separators

std::cin

#include <iostream>

int main()
{
    int i;
    char c;
    double x;
    char s[4];
    std::cout << "Enter an integer, a character,"
              << " a double and a string : " << std::endl;
    //std::cin >> i;
    //std::cin >> c;
    //std::cin >> x;
    //std::cin >> s;
    // or, equivalently
    std::cin >> i >> c >> x >> s;
    std::cout << "Entered " << i << ' ' << c
              << ' ' << x << ' ' << s << std::endl;

    return 0;
}
        

std::cin

There can be overflown when reading into a char array

Use std::cin.get(c) to capture a single character

Use std::cin.get(s, size + 1) to capture a character array with a specific size

Use std::cin.getline() to capture strings with spaces

Flush the buffer with std::cin.ignore()if not sure!

std::cin

#include <iostream>
#include <limits> //defines std::numeric_limits

int main()
{
    char c;
    char s[64];
    std::cout << "Sequence of characters: ";
    std::cin.get(c);
    std::cin.get(s, 8);
    std::cout << "Input " << c << ", and "
              << s << std::endl;

    std::cin.ignore(
        std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "Enter a string with spaces: ";
    std::cin.getline(s, 64);
    std::cout << "Input: " << s << std::endl;

    return 0;
}
        

std::cout

std::cout is frequently used with the overloaded insertion operator << (which can be chained)

std::cout's output can be formatted using flags such as fixed, setprecision, defaultfloat, etc.

The std::endl manipulator inserts a newline and flushes the buffer

std::cout

#include <iostream>
#include <iomanip> //for setprecision

int main()
{

    float pi = 3.141592653, e = 2.718281828,
          golden_ratio = 1.618033988, my_number;

    std::cout << std::setprecision(4) << std::fixed
              << "Pi with four decimal digits is: "
              << pi << std::endl;
    std::cout << std::setprecision(2) << std::scientific
              << "Euler's number in sci notation is: "
              << e << std::endl;
    std::cout << std::defaultfloat << "The gold ratio is: "
              << golden_ratio << std::endl;

    std::cout << "Enter a float: " << std::endl;
    std::cin >> my_number;
    std::cout << std::setprecision(4) << std::fixed
              << "My number with four decimal digits is: "
              << my_number << std::endl;
    std::cout << std::defaultfloat << "My number is: "
              << my_number << std::endl;

    return 0;
}
              

FSTREAM

Overview

C++ has a library to deal with file input/output (IO) operations: fstream

It allows developers to open files for reading and writing in several modes:

  ios::in open for reading

  ios::out open for writing

  ios::app open for appending

ofstream

An ofstream object can be used to write files

It contains methods to open a file for streaming: open(), closing it: close(), as well as for checking if a file is open: is_open()

It overloads the insertion operator: << stream operator to write into a file

Writing into a file

#include <iostream>
#include <fstream>

int main()
{
    std::ofstream write_file;

    write_file.open("test.txt", std::ios::out);
    if (write_file.is_open())
    {
        write_file << "Add a line of text to file"
                   << std::endl;
        write_file << "Second line of text to file"
                   << std::endl;
        std::cout << "File written!" << std::endl;
    }
    else
    {
        std::cout << "Could not open file"
                  << std::endl;
    }
    write_file.close();

    return 0;
}
      

ifstream

An ifstream object can be used to read files

It also contains methods to open a file for streaming: open(), closing it: close(), as well as for checking if a file is open: is_open()

It overloads the extraction operator: >>, stream operators to read from a file

Use getline() in case there are spaces in the captured array

Reading from a File

#include <iostream>
#include <fstream>

int main()
{
    std::ifstream read_file;

    read_file.open("test.txt", std::ios::in);
    if (read_file.is_open())
    {
        char aux[128];
        // read one word from the file
        read_file >> aux;
        std::cout << aux << std::endl;
        // read whole file word by word
        while (read_file >> aux)
        {
            std::cout << aux << std::endl;
        }
    }
    else
    {
        std::cout << "Could not open file"
                  << std::endl;
    }
    read_file.close();

    return 0;
}
      

Suggested Reading

IOStream Refinements

File Handling in C++