10
文件 IO 流与常用标准库
IO Streams · string · chrono · optional
C++ 的 IO 是一套"流":数据像水流一样从文件流进程序、再流出去。文件读写用 ifstream/ofstream,格式化用 <iomanip> 或现代的 std::format。
读写文件
#include <fstream>
#include <string>
#include <iostream>
int main() {
// 写文件
std::ofstream out("note.txt");
out << "第一行\n第二行\n";
// 读文件,一行一行读
std::ifstream in("note.txt");
std::string line;
while (std::getline(in, line)) {
std::cout << "读到:" << line << "\n";
}
}
现代常用库速览
| 库 / 类型 | 干什么 |
|---|---|
std::string | 比 C 的 char[] 好用太多:自动扩容、有 += / substr / find。别再用 char 数组拼字符串。 |
std::string_view(C++17) | 字符串的只读视图,不拷贝。只读字符串当参数传它,又快又省。 |
std::optional<T>(C++17) | "可能有值,也可能没有"。替代返回 -1 表示错误。比如查不到用户就返回 nullopt。 |
std::variant(C++17) | 类型安全的 union:一个变量可能是 int 或 string,但编译器帮你查。 |
std::any(C++17) | 能装任意类型的盒子,用时再取出来。 |
<chrono>(C++11) | 计时、时间点,高精度。 |
<random>(C++11) | 真随机数(mt19937),比老 rand() 均匀且安全。 |
<functional> | std::function(装任何可调用对象)、std::bind。 |