Learning of C++primer|section1.2. A First Look at Input/Output


1.2. A First Look at Input/Output

C++ does not directly define any statements for input or output (IO), this functionality is provided by the standard library .
The IO library provides a lot of facilities. However, for many applications, including the examples in this book, the programmer only needs to understand some basic concepts and operations.

Most of the examples in this book use the iostream library, which handles formatted input and output .
The basis of the iostream library is two types named istream and ostream , which represent input and output streams, respectively.
A stream is a sequence of characters to be read from or written to some IO device. The term "stream" attempts to illustrate that characters are produced or consumed sequentially over time.

1.2.1. Standard Input and Output Objects

The standard library defines 4 IO objects. An object of type istream named cin (pronounced see-in) is used when processing input. This object is also called standard input .
Output is processed using an object of type ostream named cout (pronounced see-out) , also known as standard output . The standard library also defines two other ostream objects, named cerr and clog (pronounced "see-err" and "see-log", respectively). The cerr object, also known as standard error , is usually used to output warning and error messages to the user of the program. The clog object is used to generate general information about program execution.

Typically, the system associates these objects with the window in which the program is executed. In this way, when we read from cin , the data is read from the window that executes the program, and when we write to cin , cerr , or clog , the output is written to the same window. Most operating systems provide a way to redirect input or output streams when running a program. These streams can be associated with selected files using redirection.


1.2.2. A program that uses the IO library

So far, we've seen how to compile and execute a simple program that does nothing. In the opening bookstore problem, there are records with the same ISBN that need to be aggregated, which means that it is necessary to figure out how to add up the number of books sold.

To figure out how to solve this problem, let's first look at how to add two numbers. We can use the IO library to augment the main program to ask the user to give two numbers and output their sum:
#include <iostream>
int main() { std::cout << "Enter two numbers:" << std::endl; int v1, v2;
                                                    std::cin >> v1 >> v2;
                                                    std::cout << "The sum of " << v1 << " and " << v2 << " is " << v1 + v2 << std::endl;
                                                    return 0; }       


The program first displays the prompt on the user's screen:

      Enter two numbers:


The program then waits for user input. If the user enters

      3 7


Following a newline, the program produces the following output:

      The sum of 3 and 7 is 10

The first line of the program is a preprocessing directive :

      #include <iostream>

Tell the compiler to use the iostream library. The name in angle brackets is one. header file . Programs that use library tools must include the relevant header files.
The #include directive must be written on a separate line - the header file name and the #include must be on the same line. In general, #include directives should appear outside of any function. And by convention, all #include directives for a program appear at the beginning of the file.

              std::cout << "Enter two numbers:" << std::endl;
    Equivalent to std::cout<<"Enter two numbers:";
              std::cout<<endl;
    endl is a special value, called an operator, that has the effect of wrapping a line when it writes to the input and output streams, and flushes the buffer associated with the device.
Writing to a Stream
write to stream

The first statement in the main function body executes an expression . In C++, an expression consists of one or more operands and usually an operator. The expression for this statement uses the output operator ( << operator) to print a prompt on standard output:

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

This statement uses the output operator twice. Each output operator instance accepts two operands: the left operand must be an ostream object; the right operand is the value to output. The operator writes its right operand to the ostream object that is its left operand.

In C++, every expression produces a result, usually the value produced by applying an operator to its operand. When the operator is an output operator, the result is the value of the left operand. That is, the value returned by an output operation is the output stream itself.



Now that the output operator returns its left operand, we can chain output requests together. The statement that outputs the prompt is equivalent to

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


Since ( (std::cout << "Enter two numbers:") ) returns its left operand std::cout , this statement is equivalent to

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


endl is a special value called a manipulator that , when written to the output stream, has the effect of wrapping the output and flushing the buffer associated with the device . By flushing the buffer, the user can immediately see the output written to the stream.

Programmers often insert print statements during debugging. Such statements should always flush the stream. Forgetting to do so may cause output to be left in the buffer if the program crashes, leading to incorrect inferences about where the program crashed.

Programmers often insert output statements during debugging that should flush the output stream. Forgetting to flush the output stream can cause the output to stay in the buffer, which, if the program crashes, will cause the program to incorrectly infer the crash location.
Using Names from the Standard Library
use the name from the standard library

The attentive reader will notice that std::cout and std::endl are used in this program , not cout and endl .
The prefix std:: indicates that cout and endl are defined in namespace std . Using namespaces programmers can avoid unintentional conflicts with names defined in libraries. Because the names defined by the standard library are defined in namespaces, we can use the same names for our own purposes.

A side effect of the standard library's use of namespaces is that when we use a name from the standard library, we must explicitly express that we are using a name in the std namespace . The writing of std::cout uses the scope operator ( scope operator , :: operator), which means that the cout defined in the namespace std is used . We'll learn how to avoid this verbose syntax often used in programs in Section 3.1 .

Reading From a Stream
read stream

After the prompt is output, the data input by the user will be read. First define two variables named v1 and v2 to hold the input:

      int v1, v2;


Define these variables as type int , a built-in type that represents integer values . These variables are uninitialized , meaning they are not assigned initial values. These variables are read in a value when they are first used, so they can have no initial value.

The next statement reads the input:

      std::cin >> v1 >> v2;


The input operator (>>operator) behaves like the output operator. It accepts anistreamobject as its left operand and an object as its right operand, and it reads data from theistreamoperand and saves it into the right operand. Like output operators, input operators return their left operand as the result. Since the input operator returns its left operand, we can combine the sequence of input requests into a single statement. In other words, this input operation is equivalent to:

      std::cin >> v1;
      std::cin >> v2;


The effect of the input operation is to read two values ​​from standard input, placing the first in v1 and the second in v2 .

Completing the Program
complete the program

All that's left is to output the result:

     std::cout << "The sum of " << v1 << " and " << v2
               << " is " << v1 + v2 << std::endl;


Although this statement is longer than the one that prints the prompt, there is no conceptual difference. It outputs each operand to standard output. Interestingly, the operands are not all values ​​of the same type, some are string literals . E.g

   "The sum of "

and others are various int values, such as v1, v2, and the result of evaluating the arithmetic expression:

其他是各种 int 值,如 v1v2 以及对算术表达式

   v1 + v2

The iostream library defines versions of the input and output operators that accept all of the built-in types.

求值的结果。iostream 库定义了接受全部内置类型的输入输出操作符版本。

When writing a C++ program, in most places that a space appears we could instead use a newline. One exception to this rule is that spaces inside a string literal cannot be replaced by a newline. Another exception is that spaces are not allowed inside preprocessor directives.

在写 C++ 程序时,大部分出现空格符的地方可用换行符代替。这条规则的一个例外是字符串字面值中的空格符不能用换行符代替。另一个例外是空格符不允许出现在预处理指示中。


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325728313&siteId=291194637