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/