Standard Input and Output Objects in C++

Standard Input and Output Objects

The library iostream defines four IO objects.

Input (istream objects):

cin This object is also referred to as the standard input.

Output (ostream objects):

cout This object is also referred to as the standard output.

cerr referred to as the standard error, for warning and error messages

clog for general information about the excution of the program.

Ordinarily, the system associates each of these objects with the window in which the program is executed. So, when we read from cin, data are read from the window in which the program is executing, and when we write to cout, cerr, or clog, the output is written to the same window.

Writing to a Steam

std::cout << "Enter two numbers:" << std::endl;

equals

(std::cout << "Enter two numbers:") << std::endl;

The << operator takes two operands: The left-hand operand must be an ostream object; the right-hand operand is a value to print. The result of the output operator is its left-hand operand.

endl, which is a special value called a manipulator. Writing endl has the effect of ending the current line and flushing the buffer associated with that device. Flushing the buffer ensures that all the output the program has generated so far is actually written to the ouput stream, rather than sitting in memory waiting to be written.

Programmers ofthen add print statements during debugging. Such statements should always flush the stream. Otherwise, if the program crashes, output may be left in the buffer, leading to incorrect inferences about where the program crashed.

Reading an Unknown Number of Inputs

 

#include <iostream>

int main(){
    int sum = 0, value = 0;
    // read until end-of-file, caculating a running total of all values read
    while(std::cin >> value){
        sum + = value;
    }
    std::cout << "Sum is: " << sum << std::endl;
    return 0;
}

This confidtion for while tests std::cin.

When we use an istream as a condition, the effect is to test the state of the stream. If the stream is valid–that is, if the stream hasn’t encountered an error–then the test succeeds. An istream becomes invalid when we hit end-of-file or encounter an invalid input, such as reading a value that is not an integer. An istream that is in an invalid state will cause the condition to yield false.

Entering an end-of-file from the keyboard

When we enter input to a program from the keyboard, different operationg systems use different conventions to allow us to indicate end-of-file. On Windows systems, it is Ctrl+Z. On Unix systems, including on Mac OS X machines, end-of-file is usually Ctrl+D.

发表评论

电子邮件地址不会被公开。 必填项已用*标注

20 − 17 =

48 − = 40