C++ learning 3 - input and output

In the C language, the formatted input and output functions printf and scanf are usually used to input or output data or information. In the C++ language, we can still use this set of input and output libraries of the C language, but the C++ language has customized a new set of input and output libraries that are easier to use.

In a C++ program, input and output can be regarded as a series of data streams, input can be regarded as a series of data streams input into the program from a file or keyboard, and output can be regarded as a series of data streams output from the program to the display or to a file.

When writing a C++ program, if you need to use input and output, you need to include the header file iostream. Objects for input and output are defined in iostream, such as common cin for standard input, cout for standard output, and cerr for standard error.

It should be emphasized that cin, cout, and cerr are not keywords in C++. Their essence is function calls. Their implementation uses C++ operator overloading. These knowledge points will be introduced one by one in the future. The output destinations of cout and cerr are both displays, but the difference is that cout is buffered, while cerr is not buffered.

When we use cout for output, we need to use the "<<" operator immediately, and when we use cin for input, we need to use the ">>" operator immediately. These two operators can analyze the data type processed by themselves, so there is no need to We set up input and output formatting statements like scanf and printf.

C++ simple input and output code example:

#include <iostream>

int main()
{
    int x;
    std::cin >> x;
    std::cout << "123 is output!" << x << std::endl ;

    return 0;



    使用C++ cin 连续输入数据:
    
#include<iostream>
using namespace std;

int main()
{
    int sum = 0;
    int val = 0;
    cout<<"Please input a number :"<<endl;
    
    while(cin>>val)
    {
        sum += val;
        cout<<"Please input next number :"<<endl;
    }
    
    cout<<"The sum of all number is sum = "<<sum<<endl;
    return 0;
}

Guess you like

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