c++ - 我什么时候应该 `#include <ios>` , `#include <iomanip>` 等?

标签 c++ header-files iostream

C++ 标准库提供了以下与 iostream 相关的头文件:

<ios>
<iosfwd>
<istream>
<ostream>
<streambuf>
<iostream>
<fstream>
<sstream>
<strstream> [deprecated]
<iomanip>

什么时候最简单、最明智的规则是#include这些标题中的哪一个? (如果不同版本的 C++ 的答案不同,我对 C++17 最感兴趣。而且我最感兴趣的是保证工作的内容,而不是哪些 header 恰好包含其他libstdc++ 或其他文件中的 header 。)

我愿意相信我总能熬过<iostream> , <fstream> (仅当我使用 fstreams 时),和/或 <sstream> (仅当我使用 stringstreams 时)。这似乎适用于这样的简单程序

#include <iostream>

int main() {
    std::cout << std::hex << 42 << std::endl << std::flush;
}

但如果我添加 std::setw(42)到那个程序,然后它停止编译;我需要包括 <iomanip>在那种情况下也是如此。

所以规则似乎是“包括 <iostream><fstream> 和/或 <sstream> ;如果您使用任何 these 操纵器,还包括 <iomanip>。”

如果我虔诚地遵守这条规则,我会不会遇到我需要包含<ios>的情况? , <iosfwd> , <istream> , <ostream> , 和/或 <streambuf>在我的应用程序代码中?

最佳答案

If I follow this rule religiously, will I ever run into a case where I need to include <ios>, <iosfwd>, <istream>, <ostream>, and/or <streambuf> in my application code?

嗯, <iostream> 包括 <ios> , <streambuf> , <istream> , 和 <ostream> .和 <iosfwd>只是前向声明,所以你也不需要那个。所以……我想,是的。

<fstream> 为您提供所有与文件相关的内容:filebuf , ifstream , ofstream , 和 fstream (以及他们广泛的同行)。

<sstream> 同样给你所有的stringstream类型和 stringbuf .

剩下的就是记住 <iomanip> 中的内容,这不是那么多,但你总是可以查一下。

关于c++ - 我什么时候应该 `#include <ios>` , `#include <iomanip>` 等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45624450/

相关文章:

c++ - 如何将转换为 const char (c++) 的结构转换为 struct objective-c

c++ - 在 C++ 头文件中包含 fstream 或 ifstream

c++ - 该项目不会将整数作为二进制读取并将它们作为二进制输出到新文件

c++ - 为什么 `cin >> noskipws` 不等待输入?

c++ - 在 C++ 中创建对象的拷贝

c++ - 指向类成员函数的指针

c++ - 在不同 block 之间使用 C++ 类对象

c++ - 当您只能使用 C 文件时,为什么要创建新的头文件?

c - 调用内联函数时 undefined reference

c++ - 为什么在 C++11 中流仍然转换为指针?