> 文章列表 > C++基础知识【10】I/O操作

C++基础知识【10】I/O操作

C++基础知识【10】I/O操作

目录

一、概述

二、标准输入输出

三、文件输入输出流

四、格式化输出

五、二进制输入输出

六、一些新特性

6.1、std::to_string()和std::stoi()函数

6.2、std::put_time()函数

6.3、std::filesystem库

七、注意事项


一、概述

        C++ I/O(输入输出)是 C++ 语言中一个非常重要的部分,它允许我们从键盘、文件或其他设备读取数据,也可以将数据输出到屏幕、文件或其他设备。

        流(stream):C++ I/O 中的基本单位,表示输入或输出数据的流。输入流用于读取数据,输出流用于将数据写入到指定的设备中。

二、标准输入输出流

        在 C++ 中,标准输入输出流是指 std::cin 和 std::cout。std::cin 表示标准输入流,用于从键盘读取数据;std::cout 表示标准输出流,用于将数据输出到控制台。

        使用标准输入输出流需要包含头文件 #include <iostream>。

        以下是一个简单的例子:

#include <iostream>
using namespace std;int main() {int num;cout << "Enter a number: ";cin >> num;cout << "You entered: " << num << endl;return 0;
}

在上面的例子中,我们使用 std::cin 从键盘读取一个整数,然后使用 std::cout 将该整数输出到屏幕上。

三、文件输入输出流

        除了标准输入输出流之外,C++ 还提供了文件输入输出流,用于读取和写入文件。C++ 中提供了多个文件输入输出流,其中最常用的是 ifstream 和 ofstream。ifstream 表示输入文件流,用于从文件中读取数据;ofstream 表示输出文件流,用于将数据写入到文件中。

        以下是一个简单的例子:

#include <iostream>
#include <fstream>
using namespace std;int main() {ofstream outfile("example.txt");outfile << "Hello, world!" << endl;outfile.close();return 0;
}

在上面的例子中,我们使用 ofstream 类打开一个名为 example.txt 的文件,并将字符串 "Hello, world!" 写入该文件中。最后,我们关闭文件。

四、格式化输出

        C++ I/O 允许我们以指定的格式将数据输出到屏幕或文件中。以下是一个例子,展示了如何使用 std::cout 进行格式化输出:

#include <iostream>
#include <iomanip>
using namespace std;int main() {int num = 123;cout << "Decimal: " << num << endl;cout << "Hexadecimal: " << hex << num << endl;cout << "Octal: " << oct << num << endl;cout << "Floating-point: " << fixed << setprecision(2) << 123.456 << endl;return 0;
}

在上面的例子中,我们使用 std::cout 输出一个整数,以十进制、十六进制和八进制形式输出该整数,以及输出一个保留两位小数的浮点数。

五、二进制输入输出

        C++ I/O 允许我们以二进制形式读取和写入数据。以下是一个例子,展示了如何使用二进制输入输出:

#include <iostream>
#include <fstream>
using namespace std;struct Person {char name[20];int age;
};int main() {Person p1 = {"Alice", 25};ofstream outfile("example.bin", ios::binary);outfile.write((char*)&p1, sizeof(p1));outfile.close();Person p2;ifstream infile("example.bin", ios::binary);infile.read((char*)&p2, sizeof(p2));infile.close();cout << "Name: " << p2.name << endl;cout << "Age: " << p2.age << endl;return 0;
}

在上面的例子中,我们定义了一个名为 Person 的结构体,包含一个 char 类型的 name 数组和一个 int 类型的 age 变量。我们首先使用 ofstream 类打开一个名为 example.bin 的文件,并将一个 Person 类型的变量写入该文件中。我们使用了 std::ios::binary 标志来指示我们要进行二进制输出。接着,我们使用 ifstream 类打开该文件并读取 Person 类型的变量。最后,我们将读取到的数据输出到屏幕上。

六、一些新特性

6.1、std::to_string()和std::stoi()函数

        std::to_string()函数可以将数字转换为字符串类型,而std::stoi()函数可以将字符串类型转换为整数类型。

例如,以下代码将整数变量x转换为字符串类型并输出:

int x = 123;
std::string str = std::to_string(x);
std::cout << str << std::endl; // 输出"123"

以下代码将字符串类型转换为整数类型并输出:

std::string str = "123";
int x = std::stoi(str);
std::cout << x << std::endl; // 输出123

6.2、std::put_time()函数

        std::put_time()函数可以格式化时间并输出为字符串类型。

#include <iostream>
#include <iomanip>
#include <ctime>int main() {std::time_t now = std::time(nullptr);std::tm* localTime = std::localtime(&now);std::cout << "Current date and time: "<< std::put_time(localTime, "%Y-%m-%d %H:%M:%S") << std::endl;return 0;
}

该代码使用了std::put_time()函数来格式化时间,并使用"%Y-%m-%d %H:%M:%S"格式将时间输出为字符串类型。运行该程序,将会输出当前时间,例如:

Current date and time: 2023-04-19 09:26:30

6.3、std::filesystem库

        std::filesystem库提供了一套易于使用的API,用于管理和操作文件系统中的文件和目录。该库在C++17中被引入,并在C++20中进行了扩展。使用std::filesystem库,我们可以轻松地创建、删除、移动和复制文件和目录。

例如,以下代码使用std::filesystem库创建一个名为"example.txt"的文件,并向其中写入一些数据:

#include <iostream>
#include <fstream>
#include <filesystem>int main() {std::filesystem::path filePath = "example.txt";std::ofstream outFile(filePath);if (outFile.is_open()) {outFile << "Hello, world!\\n";outFile.close();std::cout << "File created successfully!" << std::endl;} else {std::cout << "Failed to create file!" << std::endl;}return 0;
}

该代码使用std::filesystem库中的std::filesystem::path类创建了一个路径对象,然后使用std::ofstream类创建了一个输出文件流,并将路径对象传递给构造函数。在成功创建文件流后,我们使用流运算符向文件中写入了一些数据,并在操作完成后关闭了文件。运行该程序,将会在当前目录下创建一个名为"example.txt"的文件,并向其中写入"Hello, world!"。

七、注意事项

        在使用 C++ I/O 进行输入输出操作时,我们需要注意以下几个方面:

        1、异常处理:在进行文件操作时,可能会出现一些错误,例如文件无法打开或读取。因此,我们需要在代码中加入适当的异常处理,以便在出现错误时能够及时处理异常。

        2、格式化输出:在进行格式化输出时,我们需要确保输出的格式与数据类型相匹配。否则,可能会出现输出数据与预期不符的情况。

        3、二进制输入输出:在进行二进制输入输出时,我们需要注意保持读取和写入数据的字节数相同,以确保数据能够正确地被写入和读取。

        4、缓冲区清空:在使用 std::cout 进行输出时,输出的数据会被缓存在缓冲区中,直到缓冲区被填满或者手动进行清空操作。因此,如果我们需要立即将数据输出到屏幕上,我们需要手动进行缓冲区清空操作。

        5、不要忘记关闭文件:在进行文件输入输出操作时,我们需要在操作完成后及时关闭文件。否则,可能会出现文件被占用的情况,导致其他程序无法进行文件读取和写入操作。