问题描述
我想问一个关于C ++中的ios库的问题。
我是C ++的初学者,正在学习输入/输出流-iostream
考虑以下代码:
#include <iostream>
#include <iomanip> // required for manipulators
int main () {
std::cout << "no boolalpha - default (10 == 10): " << (10 == 10) << std::endl;
std::cout << "no boolalpha - default (10 == 20): " << (10 == 20) << std::endl;
// set to true/false formatting
std::cout << std::boolalpha;
std::cout << "boolalpha (10 == 10): " << (10 == 10) << std::endl;
std::cout << "boolalpha (10 == 20): " << (10 == 20) << std::endl;
// setf method
std::cout.setf(std::ios::boolalpha);
std::cout << "boolalpha (10 == 10): " << (10 == 10) << std::endl;
std::cout << "boolalpha (10 == 20): " << (10 == 20) << std::endl;
// reset to default 0/1
std::cout << std::resetiosflags(std::ios::boolalpha);
std::cout << "Default (10 == 10): " << (10 == 10) << std::endl;
std::cout << "Default (10 == 20): " << (10 == 20) << std::endl;
return 0;
我知道我可以通过将std::boolalpha
插入std::out
中来切换输出流以显示布尔输出。
但是,我也可以使用setf
方法来切换标志:
std::cout.setf(std::ios::boolalpha);
但是,尽管我还没有在头文件中导入setf
库,但提供给ios
方法的参数引用了ios
库类。
此代码仍然有效。
为什么这样做?我以为我需要声明<ios>
头文件来使此工作有效,尽管代码可以完美地编译。
解决方法
<iostream>
标头包含<ios>
,reference。