1.4.  Standard Input and Output

[ fromfile: cppintro.xml id: stdinout ]

  1. cin, console input, the keyboard by default.

  2. cout, console output, the console screen by default.

  3. cerr, console error, another output stream to the console screen that flushes more often and is normally used for error messages.

  cout << "The cost is $" << 23.45 << " for " << 6 << " items." << '\n';
  

Example 1.2. src/iostream/io.cpp

#include <string>
#include <iostream>

int main() {
    using namespace std;
    const int THISYEAR = 2011;  
    string yourName;
    int birthYear;

    cout << "What is your name? "  << flush;
    cin >> yourName;

    cout << "What year were you born? " ;
    cin >> birthYear;

    cout << "Your name is " << yourName
            << " and you are approximately " 
            << (THISYEAR - birthYear)
            << " years old. " << endl;
}

[Note] For Windows/MSVC Users

By default, MSVC generates applications with no console support. This means that you cannot use the standard i/o/error streams unless you tell MSVC to build a console application. See the note [ CONFIG += console (for MSVC users) ] in Section 1.6.



[2] Manipulators are function references that can be inserted into an input or output stream to modify its state. We discuss these further in Section 1.9.

[3] We discuss classes in detail in Chapter 2. For now, you can think of a class as a data type with built-in functions.