Introduction to data input and output in C++

Introduction to data input and output in C++

The files involved in the input and output of data in C++

<iostream>: This is one of the most commonly used header files in the C++ standard library. It contains classes and objects that perform standard input and output operations, such as std::cin, std::cout, std::endl, etc.

<iomanip>: This header file provides some functions and flow control symbols for controlling the input and output formats, such as std::setprecision, std::setw, std::fixed, etc.

<fstream>: This header file is used for file input and output operations. It provides input and output stream classes for reading and writing files, such as std::ifstream, std::ofstream, etc.

<sstream>: This header file defines classes for string streams, such as std::istringstream, std::ostringstream, etc. They are handy for converting data from strings to other types, or converting data of other types to strings.

<cstdio> or <stdio.h>: This is a header file in C language, which can also be used in C++. It provides some input and output functions related to the C standard library, such as scanf, printf, fgets, fputs, etc.

It is necessary to select the appropriate header file according to actual needs to perform data input and output operations. For example, if you only need to perform standard input and output, you only need to include <iostream>; if you need to read and write files, you need to include <fstream>; if you need to perform string stream operations, you need to include <sstream>, etc.

The following introduces several basic ways of input and output of data in several C++.

cin and cout , getline function and puts function using <iostream> header file

Cin and cout: These are the input and output stream objects provided by the C++ standard library, which are used to read data from standard input and write data to standard output. For example, to read an integer you can use cin and the >> operator, and to output an integer you can use cout and the << operator:

#include <iostream>

int main() {
    int num;
    std::cout << "请输入一个整数: ";
    std::cin >> num;
    std::cout << "您输入的整数是: " << num << std::endl;

    return 0;
}

In the above example, we read an integer from standard input using std::cin and output it to standard output using std::cout.

The getline function is used to read a line of string from the input stream and save it to the specified variable. The puts function is used to output a string to standard output. The getline function can be used to read a line of strings, and the puts function can be used to output a string. The getline function reads a line of characters from the input stream until a newline or end-of-file character (\n or EOF) is encountered. The puts function prints a string to standard output with a newline automatically added. It should be noted that the puts function can only output C-style strings, and the string type string needs to be converted into a C-style character pointer, and the c_str() method of the string can be used. The sample code for using the two functions getline and puts is as follows:

#include <iostream>

int main() {
    std::string str;
    std::cout << "请输入一行字符串: ";
    std::getline(std::cin, str); // 读入一行字符串
    std::cout << "您输入的字符串是: " << str << std::endl;

    const char* cstr = str.c_str();
    std::puts(cstr); // 输出字符串

    return 0;
}

Test run:

The function of the line of code "const char* cstr = str.c_str();" in the example is to convert the string str of type std::string into a C-style string (null-terminated character array).

Why use the c_str() function? Because the parameter accepted by the std::puts() function is a C-style string (that is, a null-terminated character array), rather than the C++ std::string type. So, before calling the std::puts() function, we need to use the c_str() function to get a C-style string. The std::string type in C++ provides a member function c_str(), which returns a constant pointer to string data. By calling the c_str() function, we can get the address of the character array stored in the std::string object.

Use getchar , putchar , scanf , printf functions of <cstdio> header file

The getchar and putchar functions are two commonly used character input and output functions.

The getchar() function is used to read a single character from the standard input stream (usually the keyboard). It does not require any parameters and waits for the user to enter characters before continuing program execution. Example usage is as follows:

#include <cstdio>

int main() {
    char c = getchar(); // 从标准输入读取一个字符
    putchar(c); // 将字符输出到标准输出
    return 0;
}

The putchar() function is used to output a character to the standard output stream (usually the console). Example usage is as follows:

#include <cstdio>

int main() {
    char c = 'A';
    putchar(c); // 将字符 'A' 输出到屏幕
    return 0;
}

By the way:

getchar() and putchar() were originally designed to handle ASCII characters, but they are also capable of handling Chinese characters. Chinese characters usually use multi-byte encoding (such as UTF-8), how to understand?

 The getchar() and putchar() functions can handle Chinese characters because they are implemented through the character input and output functions provided by the underlying operating system or compiler. The underlying character input and output functions may vary according to different operating systems or compilers, and problems may occur with some special characters or encoding methods. So when dealing with Chinese characters, it is better to use more advanced input and output functions that support Chinese characters, such as using std::cin and std::cout in the <iostream> header file.

scanf and printf are commonly used input and output functions in C language, and can also be used in C++. scanf is used to read data from standard input, and printf is used to write data to standard output. If you want to use it in C++, you need to pay attention to some details. In general, scanf and printf can be used equivalently to cin and cout. For example, you can use scanf to read an integer and printf to output an integer:

#include <cstdio>

int main() {
    int num;
    printf("请输入一个整数: ");
    scanf("%d", &num); // 读入一个整数
    printf("您输入的整数是: %d\n", num); // 输出一个整数到标准输出

    return 0;
}

It should be noted that scanf and printf need to use format strings to specify the data type of input and output, so more code needs to be written. At the same time, the input parameters of scanf need to use the "address symbol" &, while the output parameters of printf do not.

Scanf and printf formatted input and output introduction

The printf function is a function for formatted output, which can output formatted data to the console or to a file. The basic syntax is:

printf("Format control string", value1, value2, ...);

Among them, the format control string is used to specify the data type and format to be output. Value 1, value 2, etc. represent variables or constants to be output, and there can be more than one. A format control string containing the format of the output. The following conversion characters and corresponding format specifiers can be used to specify the type of output:

%d: Output as a decimal integer.

%f: Output in the form of floating point numbers.

%c: Output in the form of characters.

%s: output in the form of a string.

%p: output in the form of a pointer.

%x: Output in the form of hexadecimal numbers.

%.3f: where ".3f" is a specific format control character. ".3" indicates the precision limit, that is, three significant figures are reserved after the decimal point. And "f" means floating point type.

The scanf function is a function for formatting input, which can read data in a specified format from the console or a file.

The basic syntax is:

scanf("Format control string", address_expression1, address_expression2, ...);

Among them, the format control string is used to specify the data type and format to be input. The address expression is used to indicate the address of the variable in the memory, so that the scanf function can store the input data into the corresponding variable. A format control string containing the format of the input. The type of input can be specified using the same conversion characters and format specifiers as printf.

Here is a complete example using the scanf and printf functions:

#include <cstdio>

int main() {
    int num;
    printf("请输入一个整数: ");
    scanf("%d", &num);
    printf("您输入的整数是: %d\n", num);

    double floatingNum;
    printf("请输入一个浮点数: ");
    scanf("%lf", &floatingNum);
    printf("您输入的浮点数是: %.2f\n", floatingNum);

    return 0;
}

In this example, printf is used to output the prompt, and then scanf is used to read the data from the user input. When reading an integer, use the %d format specifier, and pass the address of the variable to scanf through the & address operator; when reading a floating-point number, use the %lf format specifier, and also need to use the & address operator to pass the variable address . Use printf to format the read data to the screen. Note that when outputting floating-point numbers, we use the %.2f format control to limit the display to only two decimal places.

[The function of taking the address character "&" is to take the address of the variable. An address identifies a location in memory and is equivalent to a container (such as a "box") number.
Suppose there is a variable a, which is equivalent to a container named a, &a means that the number of this container has been found, and this container can be used.

file input and output

The use of file input and output in C++ needs to include the <fstream> header file. Commonly used classes include ifstream (input file stream) and ofstream (output file stream). You can use them to open files, read and write files, and close files—the open, read, write, and close functions, etc. ) and other operations. Here's an example code that copies the contents of one file into another:

#include <fstream>
#include <iostream>

int main() {
    std::ifstream fin("input.txt"); // 打开输入文件
    std::ofstream fout("output.txt"); // 打开输出文件
    
    int n;
    while (fin >> n) { // 从输入文件读入整数并写入到输出文件
        fout << n << " ";
    }
    
    fin.close(); // 关闭输入文件
    fout.close(); // 关闭输出文件
    return 0;
}

C++ 's <iomanip> header file format input and output function

The <iomanip> header file is often used to control the format of the standard output stream, such as setting the number of digits when outputting floating-point numbers, adjusting alignment, setting padding characters, and so on. https://en.cppreference.com/w/cpp/header/iomanip or https://cplusplus.com/reference/iomanip/

Included functions:

setiosflags: Set the specified format flags, multiple flags can be combined by the bit OR operator (|).

resetiosflags: Resets the specified format flags.

setbase: Set the base of the integer output, such as binary, decimal, octal or hexadecimal.

setfill: Set the filling character, which is used to fill the blank position when the field width is insufficient.

setprecision: Set the precision after the decimal point of the floating-point number output.

setw: Set the width of the field, affecting the spacing between each field during output.

get_money: Get a monetary value from the input stream.

put_money: Writes a monetary value to the output stream.

get_time: get the date and time from the input stream.

put_time: Write date and time to the output stream.

Here is a sample program:

#include <iostream>
#include <iomanip>  // 必须引入此头文件才能使用格式控制符

int main() {
    int i = 123;
    double d = 3.14159265359;
    std::string str = "Hello world!";

    // 设置输出浮点数精度为三位小数
    std::cout << std::fixed << std::setprecision(3);
    // 输出浮点数,如果小数位不足三位则自动补零
    std::cout << "d = " << d << std::endl;

    // 设置输出宽度为10个字符,不足则以0填充
    std::cout << std::setw(10) << std::setfill('0') << i << std::endl;

    // 设置输出宽度为20个字符,右对齐,左边用空格填充
    std::cout << std::setw(20) << std::left << str << std::endl;

    // 设置输出方式为科学计数法,保留五位小数
    std::cout << std::scientific << std::setprecision(5) << d << std::endl;

    return 0;
}

Output result:

d = 3.142
0000000123
Hello world!
3.14159e+00

explain:

std::fixed and std::scientific are used to control the display format of output floating-point numbers, representing fixed decimal point display and scientific notation display respectively.

std::setprecision(n) is used to set the precision of floating-point numbers. In fixed or scientific mode, it will control the number of digits reserved after the decimal point.

std::setw(n) and std::setfill(c) are used to set the output width and filling characters. The width specifies the total number of digits of the output data, and the insufficient width will be automatically filled with filling characters. Both functions must be used at the same time for this to work.

std::left and std::right are used to set the output alignment, left and right. The default is right alignment.

In C++, when using the functions, variables and types provided by the standard library, you need to add the namespace identifier std:: (where "::" is the namespace qualifier). For example, to use std::cout to output information.

Using the using namespace std; declaration at the beginning of the code introduces the std namespace. In this way, the functions, variables and types of the standard library can be used directly in the subsequent code without adding std::.

To quote the standard namespace, the above example could be changed to:

#include <iostream>
#include <iomanip>  // 必须引入此头文件才能使用格式控制符
using namespace std; // 引用标准名称空间 

int main() {
    int i = 123;
    double d = 3.14159265359;
    string str = "Hello world!";

    // 设置输出浮点数精度为三位小数
    cout << fixed << setprecision(3);
    // 输出浮点数,如果小数位不足三位则自动补零
    cout << "d = " << d << endl;

    // 设置输出宽度为10个字符,不足则以0填充
    cout << setw(10) << setfill('0') << i << endl;

    // 设置输出宽度为20个字符,右对齐,左边用空格填充
    cout << setw(20) << left << str << endl;

    // 设置输出方式为科学计数法,保留五位小数
    cout << scientific << setprecision(5) << d << endl;

    return 0;
}

In-depth introduction to input and output of C++ language https://blog.csdn.net/cnds123/article/details/126358415

C++ sample code for validating user input https://blog.csdn.net/cnds123/article/details/130322634

Guess you like

Origin blog.csdn.net/cnds123/article/details/132045856