Search

13.1 — Input and output (I/O) streams

Input and output functionality is not defined as part of the core C++ language, but rather is provided through the C++ standard library (and thus resides in the std namespace). In previous lessons, you included the iostream library header and made use of the cin and cout objects to do simple I/O. In this lesson, we’ll take a look at the iostream library in more detail.

The iostream library

When you include the iostream header, you gain access to a whole heirarchy of classes responsible for providing I/O functionality (including one class that is actually named iostream). The class heirarchy for the non-file-I/O classes looks like this:

The first thing you may notice about this hierarchy is that it uses multiple inheritance (that thing we told you to avoid if at all possible). However, the iostream library has been designed and extensively tested in order to avoid any of the typical multiple inheritance problems, so you can use it freely without worrying.

Streams

The second thing you may notice is that the word “stream” is used an awful lot. At it’s most basic, I/O in C++ is implemented with streams. Abstractly, a stream can be thought of as a sequence of bytes of infinite length that is used as a buffer to hold data that is waiting to be processed.

Typically we deal with two different types of streams. Input streams are used to hold input from a data producer, such as a keyboard, a file, or a network. For example, the user may press a key on the keyboard while the program is currently not expecting any input. Rather than ignore the users keypress, the data is put into an input stream, where it will wait until the program is ready for it.

Conversely, output streams are used to hold output for a particular data consumer, such as a monitor, a file, or a printer. When writing data to an output device, the device may not be ready to accept that data yet -- for example, the printer may still be warming up when the program writes data to it’s output stream. The data will sit in the output stream until the printer begins consuming it.

Some devices, such as files and networks, are capable of being both input and output sources.

The nice thing about streams is the programmer only has to learn how to interact with the streams in order to read and write data to many different kinds of devices. The details about how the stream interfaces with the actual devices they are hooked up to is left up to the environment or operating system.

Input/output in C++

Although the ios class is generally derived from ios_base, ios is typically the most base class you will be working directly with. The ios class defines a bunch of stuff that is common to both input and output streams. We’ll deal with this stuff in a future lesson.

The istream class is the primary class used when dealing with input streams. With input streams, the extraction operator (>>) is used to remove values from the stream. This makes sense: when the user presses a key on the keyboard, the key code is placed in an input stream. Your program then extracts the value from the stream so it can be used.

The ostream class is the primary class used when dealing with output streams. With output streams, the insertion operator (<<) is used to put values in the stream. This also makes sense: you insert your values into the stream, and the data consumer (eg. monitor) uses them.

The iostream class can handle both input and output, allowing bidirectional I/O.

Finally, there are a bunch of classes that end in “_withassign”. These stream classes are derived from istream, ostream, and iostream (respectively) with an assignment operator defined, allowing you to assign one stream to another. In most cases, you won’t be dealing with these classes directly.

Standard streams in C++

A standard stream is a pre-connected stream provided to a computer program by it’s environment. C++ comes with four predefined standard stream objects that have already been set up for your use. The first two, you have seen before:

  1. cin -- an istream_withassign class tied to the standard input (typically the keyboard)
  2. cout -- an ostream_withassign class tied to the standard output (typically the monitor)
  3. cerr -- an ostream_withassign class tied to the standard error (typically the monitor), providing unbuffered output
  4. clog -- an ostream_withassign class tied to the standard error (typically the monitor), providing buffered output

Unbuffered output is typically handled immediately, whereas buffered output is typically stored and written out as a block. Because clog isn’t used very often, it is often omitted from the list of standard streams.

A basic example

Here’s an example of input and output using the standard streams:

In the next lesson, we’ll take a look at some more I/O related functionality in more detail.

13.2 -- Input with istream
Index
12.6 -- Pure virtual functions, abstract base classes, and interface classes

12 comments to 13.1 — Input and output (I/O) streams

  • sloooh

    Input three positive integers representing the sides of a traingle and determine whether they form a valid traingle. Hint:n a traingle the sum of any two sides must always be greater than the side.

    how i can make programme for this by c++ way???

    • Nick Xu

      OK,do it like this:

      //C style without C++ class,under VC++6.0
      #include
      using namespace std;
      int main()
      {
      int a,b,c;
      do{
      printf("a,b,c:\n");
      scanf("%d,%d,%d",&a,&b,&c);
      }while(!(a+b>c && a+c>b && c+b>a));
      printf("Correct!A valid traingle.\n");
      return 0;
      }

    • Nick Xu

      //run correctly
      #include
      using namespace std;
      int main()
      {
      int a,b,c;
      do{
      printf("a,b,c:\n");
      scanf("%d,%d,%d",&a,&b,&c);
      }while(!(a+b>c && a+c>b && c+b>a));
      printf("Correct!A valid traingle.\n");
      return 0;
      }

  • sloooh

    i have qustion , any one can help me???

  • saini
     what are buffered and unbuffered errors ?
    
  • Alex

    In your second line in after Streams, you have "it's"

    everyone knows possessive pronouns cannot have an apostrophe!

  • Q: What is the difference between the outputs of "cout", "cerr" & "clog" ?
    NOTE: Both of them gives exactly the same output to the screen.
    Q: Does "cerr" has any more inner workings than printing "Oops, you entered an invalid age!" to the screen?

    cout << "Oops, you entered an invalid age!" << endl;
    

    and

    cerr << "Oops, you entered an invalid age!" << endl;
    
    • There's actually very little difference between them. However, it is possible to redirect one or more of the channels to file (or printer, or network, or elsewhere). That way, you can have normal output go to one place (eg. a file) and have any errors go to another place (eg. the screen).

  • Kavitha

    cout — an ostream_withassign class tied to the standard input

    should read as

    cout — an ostream_withassign object tied to the standard output

    [ You are correct. Thanks for pointing out the mistake. -Alex ]

  • rohan

    Abstractly, a stream can .... infinite length that "us" used as a buffer
    ===>
    Abstractly, a stream can .... infinite length that "is" used as a buffer

    [ Fixed. Thanks! -Alex]

  • Giorgos

    you got a mistake here! x is not mentioned

    #include <iostream>

    int main()
    {
    using namespace std;
    cout << "Enter your age: " << endl;

    int nAge;
    cin >> nAge;

    if (nAge <= 0)
    {
    cerr << "Oops, you entered an invalid age!" << endl;
    exit(1);
    }

    cout << "You entered " << nAge << " years old" << endl;

    return 0;
    }

    [ Fixed. -Alex ]

  • ivailosp

    simple program using stringstream

    #include 
    #include 
    using namespace std;
    
    int sexy(const char* a, const char* b) {
    	stringstream tmp;
    	tmp << a;
    	int tmp1;
    	tmp >> tmp1;
    	tmp.clear();
    	tmp << b;
    	int tmp2;
    	tmp >> tmp2;
    	return tmp1+tmp2;
    }
    
    int main() {
    	char* string_one = "2123";
    	char* string_two = "234";
    	cout << sexy(string_one, string_two);
    	return 0;
    }
    

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">