<一>boolalpha可以将0,1的bool值和false,true表示做同步,如下:
bool b = true;
cout << b << " " << boolalpha << b << endl; // output:1 true
cout << "Enter a bool value: " ;
cin >> boolalpha >> b; // input:1\true\a input:false
cout << "Here u entered: " << b << endl; // output:true output:false
<二>custom允许用户自定义输出控制方式
eg1.
ostream &setup(ostream &stream) //自定义输出流控制器
{
stream.setf(ios::right); //输出向右靠拢
stream << setw(10) << setfill('$'); //其余位置设置为$号
return stream;
}
int main()
{
cout << 10 << " " << setup << 10; // output: 10 $$$$$$$$10
return 0;
}
eg2.
ostream& sethex(ostream& stream)
{
stream.setf(ios::showbase);
stream.setf(ios::hex, ios::basefield); //用十六进制插入或抽取一个整型数据
return stream;
}
int main ()
{
cout << 256 << " " << sethex << 256 << endl; //output:256 0x100
return 0;
}
注:其他标志见ios_base::fmtflags(MSDN)
eg3. 自定义个性输出1
ostream &ra(ostream &stream)
{
stream << "--> ";
return stream;
}
ostream &la(ostream &stream)
{
stream << " <--";
return stream;
}
int main()
{
cout << "AAA" << ra << 33.23 << endl; //output: AAA--> 33.23
cout << "BBB" << ra << 67.66 << la; //output: BBB--> 67.66 <--
return 0;
}
eg4.自定义个性输出2
ostream &setup(ostream &stream)
{
stream.width(10); //stream<<setw(10)
stream.precision(4);
stream.fill('*'); //stream<<setfill('*')
return stream;
}
int main()
{
cout << setup << 123.123456; // output: ******123.1
return 0;
}
<三>格式输出设置与重置
ostream &sethex(ostream &stream)
{
stream.unsetf(ios::dec | ios::oct);
stream.setf(ios::hex | ios::uppercase | ios::showbase);
return stream;
}
// Reset flags.
ostream &reset(ostream &stream)
{
stream.unsetf(ios::hex | ios::uppercase | ios::showbase);
stream.setf(ios::dec);
return stream;
}
int main()
{
cout << sethex << 100 << '\n'; //Output:0x64
cout << reset << 100 << '\n'; //Output:100
return 0;
}
<四>跳过十个输入字符
下面程序可跳过十个输入字符,不包括空格和回车。当字符数量大于10的时候按回车才能cuot出来,是从第11个字符开始输出来的
istream &skipchar(istream &stream)
{
int i;
char c;
for(i = 0; i <10; i++) stream >> c;
return stream;
}
int main()
{
char str[80];
cout << "Enter some characters: ";
cin >> skipchar >> str;
cout << str << '\n';
return 0;
}
<五>显示数的正负号
cout.setf(ios::showpos);
cout << -10 << ' ' << 10 << '\n'; //Output: -10 +10
<六>科学计数法显示数
cout.setf(ios::showpoint | ios::uppercase | ios::scientific);
cout << 100.0; //Output:1.000000E+02
<七>按行接收字符串并编号输出
对getline的理解,接收一行,以回车结尾为标志接收
string line;
int number = 0;
while( getline( cin, line))
{
cout << setw(5) << ++number << ": "
<< line << endl;
}