© Slobodan Dmitrović 2020
S. DmitrovićModern C++ for Absolute Beginnershttps://doi.org/10.1007/978-1-4842-6047-0_37

37. Input/Output Streams

Slobodan Dmitrović1 
(1)
Belgrade, Serbia
 

We can convert our objects to streams of bytes. We can also convert streams of bytes back to objects. The I/O stream library provides such functionality.

Streams can be output streams and input streams.

Remember the std::cout and std::cin? Those are also streams. For example, the std::cout is an output stream. It takes whatever objects we supply to it and converts them to a byte stream, which then goes to our monitor. Conversely, std::cin is an input stream. It takes the input from the keyboard and converts that input to our objects.

There are different kinds of I/O streams, and here we will explain two kinds: file streams and string streams.

37.1 File Streams

We can read from a file, and we can write to a file. The standard-library offers such functionality via file streams. Those files streams are defined inside the <fstream> header, and they are:
  1. a.

    std::ifstream – read from a file

     
  2. b.

    std::ofstream – write to a file

     
  3. c.

    std::fstream – read from and write to a file

     
The std::fstream can both read from and write to a file, so let us use that one. To create an std::fstream object we use:
#include <fstream>
int main()
{
    std::fstream fs{ "myfile.txt" };
}
This example creates a file stream called fs and associates it with a file name myfile.txt on our disk. To read from such file, line-by-line, we use:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
    std::fstream fs{ "myfile.txt" };
    std::string s;
    while (fs)
    {
        std::getline(fs, s); // read each line into a string
        std::cout << s << ' ';
    }
}

Once associated with a file name, we use our file stream to read each line of text from and print it out on a screen. To do that, we declare a string variable s which will hold our read line of text. Inside the while-loop, we read a line from a file to a string. This is why the std::getline function accepts a file stream and a string as arguments. Once read, we output the text line on a screen. The while loop terminates once we reach the end of the file.

To read from a file, one character at the time we can use file stream’s >> operator :
#include <iostream>
#include <fstream>
int main()
{
    std::fstream fs{ "myfile.txt" };
    char c;
    while (fs >> c)
    {
        std::cout << c;
    }
}
This example reads the file contents one character at the time into our char variable. By default, this skips the reading of white spaces. To rectify this, we add the std::noskipws manipulator to the above example:
#include <iostream>
#include <fstream>
int main()
{
    std::fstream fs{ "myfile.txt" };
    char c;
    while (fs >> std::noskipws >> c)
    {
        std::cout << c;
    }
}
To write to a file, we use file stream << operator :
#include <fstream>
int main()
{
    std::fstream fs{ "myoutputfile.txt", std::ios::out };
    fs << "First line of text." << ' ';
    fs << "Second line of text" << ' ';
    fs << "Third line of text" << ' ';
}

We associate an fs object with an output file name and provide an additional std::ios::out flag which opens a file for writing and overwrites any existing myoutputfile.txt file. Then we output our text to a file stream using the << operator .

To append text to an existing file, we include the std::ios::app flag inside the file stream constructor:
#include <fstream>
int main()
{
    std::fstream fs{ "myoutputfile.txt", std::ios::app };
    fs << "This is appended text" << ' ';
    fs << "This is also an appended text." << ' ';
}
We can also output strings to our file using the file stream’s << operator:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
    std::fstream fs{ "myoutputfile.txt", std::ios::out };
    std::string s1 = "The first string. ";
    std::string s2 = "The second string. ";
    fs << s1 << s2;
}

37.2 String Streams

Similarly, there is a stream that allows us to read from and write to a string. It is defined inside the <sstream> header, and there are three different string streams :
  1. a.

    std::stringstream - the stream to read from a string

     
  2. b.

    std::otringstream - the stream to write to a string

     
  3. c.

    std::stringstream - the stream to both read from and write to a string

     
We will describe the std::stringstream class template as it can both read from and write to a string. To create a simple string stream, we use:
#include <sstream>
int main()
{
    std::stringstream ss;
}
This example creates a simple string stream using a default constructor. To create a string stream and initialize it with a string literal, we use:
#include <iostream>
#include <sstream>
int main()
{
    std::stringstream ss{ "Hello world." };
    std::cout << ss.str();
}
Here we created a string stream and initialized it with a string literal in a constructor. Then we used the string stream’s .str() member function to print the content of the stream. The .str() member function gets the string representation of the stream. To initialize a string stream with a string we use:
#include <iostream>
#include <sstream>
int main()
{
    std::stringstream ss;
    ss << "Hello World.";
    std::cout << ss.str();
}
We use the string stream’s member function .str() to assign the string stream’s content to a string variable:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
    std::stringstream ss{ "Hello World from a string stream." };
    std::string s = ss.str();
    std::cout << s;
}
To insert data into a string stream, we use the formatted output operator <<:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
    std::string s = "Hello World.";
    std::stringstream ss{ s };
    std::cout << ss.str();
}
We can also insert values of fundamental types into a string stream using the formatted output operator <<:
#include <iostream>
#include <sstream>
int main()
{
    char c = 'A';
    int x = 123;
    double d = 456.78;
    std::stringstream ss;
    ss << c << x << d;
    std::cout << ss.str();
}
To make the output more readable, we can insert text between the variables:
#include <iostream>
#include <sstream>
int main()
{
    char c = 'A';
    int x = 123;
    double d = 456.78;
    std::stringstream ss;
    ss << "The char is: " << c << ", int is: "<< x << " and double is: " << d;
    std::cout << ss.str();
}
To output data from a stream into an object, we use the >> operator :
#include <iostream>
#include <sstream>
#include <string>
int main()
{
    std::string s = "A 123 456.78";
    std::stringstream ss{ s };
    char c;
    int x;
    double d;
    ss >> c >> x >> d;
    std::cout << c << ' ' << x << ' ' << d << ' ';
}

This example reads/outputs data from a string stream into our variables. String streams are useful for formatted input/output and when we want to convert from built-in types to a string and from a string to built-in types.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.77.71