C++ zero-based tutorial (printing in C++)


Preface

In this article, we will learn how to print data in C++. In C language, we will use hello world to print data. So how to print data in C++?

1. Code experiment

In C++, data printing is usually performed using the standard output stream (std::cout). std::cout is an output stream object in the C++ standard library, which can output data to the console or other devices. The following are some common ways of printing data:

1. Print basic data types:
In C++, you can use the insertion operator (<<) to output basic data types to std::cout. For example:

int number = 10;
std::cout << "Number: " << number << std::endl;

2. Print a string:
You can use the same insertion operator (<<) to output a string to std::cout. For example:

std::string message = "Hello, World!";
std::cout << "Message: " << message << std::endl;

3. Print the address of a variable:
To print the address of a variable, you can use the address operator (&) and output it to std::cout. For example:

int number = 10;
std::cout << "Address of number: " << &number << std::endl;

4. Formatted printing:
Formatted printing can be achieved using the flow control character in C++. For example, you can use std::setw() to set the field width, std::setprecision() to set the number of decimal places for floating point numbers, etc. For example:

double pi = 3.14159265359;
std::cout << "Value of pi: " << std::setprecision(5) << pi << std::endl;

5. Print an array:
To print an array, you can use a loop to loop through each element of the array and output it to std::cout one by one. For example:

int numbers[] = {
    
    1, 2, 3, 4, 5};
std::cout << "Numbers: ";
for (int i = 0; i < 5; ++i) {
    
    
    std::cout << numbers[i] << " ";
}
std::cout << std::endl;

Complete code:

#include <iostream>
#include <iomanip> // 用于格式化输出

int main() {
    
    
    int number = 10;
    std::string message = "Hello, World!";
    double pi = 3.14159265359;

    // 打印基本数据类型
    std::cout << "Number: " << number << std::endl;

    // 打印字符串
    std::cout << "Message: " << message << std::endl;

    // 打印变量的地址
    std::cout << "Address of number: " << &number << std::endl;

    // 格式化打印
    std::cout << "Value of pi: " << std::setprecision(5) << pi << std::endl;

    // 打印数组
    int numbers[] = {
    
    1, 2, 3, 4, 5};
    std::cout << "Numbers: ";
    for (int i = 0; i < 5; ++i) {
    
    
        std::cout << numbers[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

Two, C + + namespace

In C++, namespace is a mechanism used to resolve naming conflicts and organize code. It can encapsulate symbols such as functions, classes, variables, etc. in a specific namespace to prevent conflicts between different parts of the code.

The syntax of the namespace is as follows:

namespace namespace_name {
    
    
    // 声明和定义代码
}

The following is an explanation and usage example of C++ namespaces:

Avoid naming conflicts: Naming conflicts occur when different pieces of code use the same name. To avoid this conflict, these codes can be placed in different namespaces. For example:

namespace A {
    
    
    int value = 5;
}

namespace B {
    
    
    int value = 10;
}

int main() {
    
    
    std::cout &lt;&lt; A::value &lt;&lt; std::endl;  // 输出 5
    std::cout &lt;&lt; B::value &lt;&lt; std::endl;  // 输出 10
    return 0;
}

In the above example, A and B are two different namespaces. They both have a variable named value. Due to the existence of the namespace, the corresponding variable can be referenced through the namespace operator::, avoiding the need for naming. conflict.

Nested namespaces: Namespaces can also be nested to form more complex hierarchies. For example:

namespace A {
    
    
    namespace B {
    
    
        int value = 15;
    }
}

int main() {
    
    
    std::cout &lt;&lt; A::B::value &lt;&lt; std::endl;  // 输出 15
    return 0;
}

In the above example, namespace A has a namespace B nested inside it, and then the variables in B are accessed through nesting in the main function.

Using namespace aliases: To simplify the use of namespaces, C++ provides a namespace alias mechanism. Use the keyword namespace followed by a new name to create an alias for a namespace. For example:

namespace very_long_and_verbose_namespace {
    
    
    int value = 20;
}

// 创建别名
namespace vln = very_long_and_verbose_namespace;

int main() {
    
    
    std::cout &lt;&lt; vln::value &lt;&lt; std::endl;  // 输出 20
    return 0;
}

In the above example, an alias vln is created by namespace vln = very_long_and_verbose_namespace; so that vln can be used instead of a very long and redundant namespace name.
In summary, C++ namespaces provide an effective mechanism to avoid naming conflicts and organize related code together. Through namespaces, code can be better organized and managed, improving code readability and maintainability.

3. Comparison of printing in C++ and printing in C language

In C++, cout and printf in C language are both functions used to output information, but there are some differences in their usage and characteristics. Here is some comparison between cout and printf:
Formatted output:

cout uses the insertion operator << to output. It can directly output multiple data types, such as integers, floating point numbers, strings, etc., and will perform automatic type conversion and formatting according to the data type.
printf uses a format string as a parameter and specifies the output data type and format through format conversion specifiers (such as %d, %f, %s, etc.).

类型安全:

cout is a type-safe output method. The compiler will automatically select an appropriate output method based on the target data type, avoiding some type errors and potential security issues.
When using printf, you need to manually specify the correct format conversion specifier and corresponding parameter type. If the types do not match, it may cause output errors or undefined behavior.

可读性和易用性:

The output syntax of cout is relatively intuitive and easy to read. Using the insertion operator << can output through continuous writing without the need to manually set the format.
The formatted string of printf will bring a certain degree of complexity, requiring manual control of the correspondence between the format and parameters, which may be more cumbersome for complex output formats.

功能扩展:

cout is part of the C++ standard library and can be easily used with other standard library components, such as std::string, file streams, etc.
Printf is a function in the C standard library. It has relatively few functions and may not be flexible enough for some advanced features (such as width when formatting output, precision control, etc.).

To sum up, both cout and printf are common output functions. Which method to choose depends on the specific needs and circumstances. In C++, cout is preferred because it is more type-safe, easier to use, and integrates better with other C++ features and libraries. But in some specific scenarios, printf's formatted output function may still have its advantages and uses.

Summarize

This article will explain it here. I hope you can understand it well and try it out.

Guess you like

Origin blog.csdn.net/m0_49476241/article/details/131418000