[Learncpp Chinese Translation] [1.5 - Introduction to iostream: cout, cin and endl]

Original link: Original text link

Statement:

  • This article is intended to facilitate learning C++syntax and should not be used for any commercial purpose.
  • Due to my limited English level, there may be semantic errors in the article. If you have any questions, please refer to the original text, or point out the errors in the comments area.

1.5 - Introduction to iostream: cout, cin and endl

In this lesson, we will discuss std::cout more, we are in Hello world! Used it in! Program output text Hello world! To the console. We'll also explore how to get input from users, and we'll use it to make our programs more interactive.

I/O Library

The input/output library (io library) is part of the C++standard library that handles basic input and output. We will use the functions in this library to get input from the keyboard and output data to the console. The io part of iostream represents input/output.

To use the functions defined in iostream library, we need to include iostream headers at the top of any code file that uses the contents defined in iostream, as shown below:

#include <iostream>

// rest of code that uses iostream functionality here

std::cout

The iostream library contains some predefined variables for us to use. The most useful is std::cout, which allows us to send data to the console for printing as text. Cout stands for "character output".

To remind you, this is our Hello world program:

#include <iostream> // for std::cout

int main()
{
    std::cout << "Hello world!"; // print Hello world! to console

    return 0;
}

In this program, we include iostream so that we can access std::cout. In our main function, we use std::cout and the insertion operator (<<) to send the text Hello world! To the console to be printed.

std::cout can print not only text but also numbers:

#include <iostream> // for std::cout

int main()
{
    std::cout << 4; // print 4 to console

    return 0;
}

This results in:

4

It can also be used to print the value of a variable:

#include <iostream> // for std::cout

int main()
{
    int x{ 5 }; // define integer variable x, initialized with value 5
    std::cout << x; // print value of x (5) to console
    return 0;
}

This results in:

5

To print multiple contents on the same line,<<can use the insertion operator () multiple times in a single statement to connect (link together) multiple outputs. For example:

#include <iostream> // for std::cout

int main()
{
    std::cout << "Hello" << " world!";
    return 0;
}

The program prints:

Hello world!

This is another example. We print both text and variable values in the same statement:

#include <iostream> // for std::cout

int main()
{
    int x{ 5 };
    std::cout << "x is equal to: " << x;
    return 0;
}

The program prints:

x is equal to: 5
Related content

We're in the second.9 Lesson - Naming conflicts and namespaces are discussed in std::The actual function of prefix.

std::endl

What do you want this program to print?

#include <iostream> // for std::cout

int main()
{
    std::cout << "Hi!";
    std::cout << "My name is Alex.";
    return 0;
}

You may be surprised at the results:

Hi!My name is Alex.

Separate output statements do not produce separate output lines on the console.

If we want to print a separate output line to the console, we need to tell the console when to move the cursor to the next line.

One way is to use std::endl. When std::cout output is used, std::endl prints a new line character to the console (causing the cursor to move to the beginning of the next line). In this case, endl stands for "end line".

For example:

#include <iostream> // for std::cout and std::endl

int main()
{
    std::cout << "Hi!" << std::endl; // std::endl will cause the cursor to move to the next line of the console
    std::cout << "My name is Alex." << std::endl;

    return 0;
}

This prints:

Hi!
My name is Alex.
Tip

In the above procedure, the second std::endl It is not technically necessary because the program is immediately terminated. However, it has some useful uses.

First, it helps to show that the output line is a "complete idea" (as opposed to a partial output done somewhere later in the code). In this sense, its function is similar to the use of full stops in standard English.

Second, it positions the cursor on the next line, so that if we add additional output lines later (for example, let the program say "Goodbye!"), These lines will appear where we expect them (not appended to the previous line output).

Third, after running the executable from the command line, some operating systems will not output a new line until the command prompt is displayed again. If our program does not end with the cursor on the new line, the command prompt may appear on the previous line of the output, rather than at the beginning of the new line as expected by the user.
Best Practices

As soon as a line is output, a new line character is output.

std::endl and ' n'

Using std::endl can be a bit inefficient because it actually does two things: it moves the cursor to the next line and ensures that the output is immediately displayed on the screen (this is called refreshing the output). When using std::cout to write text to the console, std::cout often refreshes the output (if not, it usually doesn't matter). Therefore, it is not important for std::endl to refresh.

Therefore, the ' n' character is usually preferred. ' \The n 'character moves the cursor to the next line, but does not request a refresh, so it performs better without a refresh.' \The n 'character is also easier to read because it is shorter and can be embedded in existing text.

This is an example of using ' n' in two different ways:

#include <iostream> // for std::cout

int main()
{
    int x{ 5 };
    std::cout << "x is equal to: " << x << '\n'; // Using '\n' standalone
    std::cout << "And that's all, folks!\n"; // Using '\n' embedded into a double-quoted piece of text (note: no single quotes when used this way)
    return 0;
}

This prints:

x is equal to: 5
And that's all, folks!

Note that single quotes are required when using ' n' alone to move the cursor to the next line. Single quotes are not required when embedded in text that has already been double quoted.

When we enter the course on chars (4.11 -- Chars), we will introduce what ' n' is in more detail.

Best Practices

When outputting text to the console, the '\n' instead of std::endl. 
warning

'\n' Use backslash (vs C++ All special characters in) instead of forward slashes. Use forward slashes (for example“/n")May cause unexpected behavior.

std::cin

std::cin is another predefined variable defined in the iostream library. std::cout uses the insertion operator (<<) to print data to the console, while std::cin (for "character input") uses the extraction operator (>>) to read input from the keyboard. The input must be stored in the variable to use.

#include <iostream>  // for std::cout and std::cin

int main()
{
    std::cout << "Enter a number: "; // ask user for a number

    int x{ }; // define variable x to hold user input (and zero-initialize it)
    std::cin >> x; // get number from keyboard and store it in variable x

    std::cout << "You entered " << x << '\n';
    return 0;
}

Try compiling this program and running it yourself. When you run the program, line 5 will print "Enter number:". When the code reaches line 8, your program will wait for your input. Once you enter a number (and press Enter), the number you enter will be assigned to the variable x. Finally, on line 10, the program prints "You entered" followed by the number you just entered.

For example (I entered 4):

Enter a number: 4
You entered 4

This is a simple way to get keyboard input from the user, and we will use it in many future examples. Note that you do not need to use ' n' when accepting input, because users need to press the enter key to accept their input, which moves the cursor to the next line.

Just as you can output multiple texts in one line, you can also enter multiple values in one line:

#include <iostream>  // for std::cout and std::cin

int main()
{
    std::cout << "Enter two numbers separated by a space: ";

    int x{ }; // define variable x to hold user input (and zero-initialize it)
    int y{ }; // define variable y to hold user input (and zero-initialize it)
    std::cin >> x >> y; // get two numbers and store in variable x and y respectively

    std::cout << "You entered " << x << " and " << y << '\n';

    return 0;
}

This will produce the output:

Enter two numbers separated by a space: 5 6
You entered 5 and 6
Best Practices

About whether it is necessary to std::cin)There is some debate about initializing a variable immediately before giving it a user supplied value, because the user supplied value will only overwrite the initialization value. According to our previous recommendation that variables always be initialized, the best practice is to initialize variables first.

We will discuss how std::cin handles invalid inputs in a later lesson (7.16 – std::cin and handling invalid inputs).

For advanced readers

C++ I/O The library does not provide a way to enter You can accept the keyboard input method. If this is what you want, you will have to use third-party libraries. For console applications, we recommend pdcurses,FXTUI or cpp-terminal. Many graphical user libraries have their own functions to do this.

generalization

New programmers often confuse std::cin, std::cout, the insertion operator (<<), and the extraction operator (>>). This is an easy to remember method:

  • std::cin and std::cout are always on the left side of the statement.
  • std::cout is used to output a value (cout=character output)
  • std::cin is used to obtain the input value (cin=character input)
  • <<Used with std::cout, and displays the direction of data movement (if std::cout represents the console, the output data is moving from the variable to the console). std::cout<<4 Move the value of 4 to the console
  • >>Use std::cin with and display the direction of data movement (if std::cin represents a keyboard, input data is moving from the keyboard to a variable). std::cin>>x moves the value entered by the user from the keyboard to x

We will discuss operators more in Lesson 1.9 - Introduction to Text and Operators.

Tags: C++ Algorithm C

Posted by Frame on Wed, 21 Sep 2022 02:27:45 +0930