《C++Primer4》附录-标准库io库的使用

1、输出为bool类型格式为true和false,需要使用cout<< boolalpha, 取消bool字母格式输出使用  cout<<noboolalpha,

2、将整型int i = 10,按各种进制输出的格式如下:

八进制输出: cout<<oct<<i <<endl , 十六进制输出: cout<<hex<<i  <<endl; 十进制输出: cout<<dec<< i <<endl;(十进制为默认输出)

如果输出需要带上标记(0, 0x),需要声明为 cout << showbase << hex << i <<endl;  cout<< noshowbase <<endl;  //  0xa

如果标记大写,则 写为   cout<<uppercase << hex << i << endl << nouppercase <<endl;

3、 cout .precision() 返回当前精度,  cout.setpricision(12) 将当前精度设置为12位(整个浮点型数字不包括小数点)。 需要包含 #include<iomanip> 头文件。

4、采用科学计数法输出,需要声明为 cout<< scientific , 对齐则声明为 cout<<fixed, 取消这些格式还原默认的格式输出 需要调用  cout.unsetf(ostream::floatfield);

5、强制显示小数点 声明为  cout << showpointer << i; // 默认精度为6, 取消显示小数点格式:  cout << noshowpointer << i << endl;

6、填充输出用法:

#include <iomanip>
#include <iostream>

using namespace std;


void set_fill_usage()
{
	int i = -16;
	double d = 3.14159;
	//默认右边对齐
	cout<<"i: "<<setw(12)<<i<<"next col"<<endl;
	cout<<"d: "<<setw(12)<<d<<"next col"<<endl;

	//靠左边对齐
	cout<<left;
	cout<<"i: "<<setw(12)<<i<<"next col"<<endl;
	cout<<"d: "<<setw(12)<<d<<"next col"<<endl;

	//靠右边对齐
	cout<<right;
	cout<<"i: "<<setw(12)<<i<<"next col"<<endl;
	cout<<"d: "<<setw(12)<<d<<"next col"<<endl;

	//负数符号靠左,数字靠右
	cout<<internal;
	cout<<"i: "<<setw(12)<<i<<"next col"<<endl;
	cout<<"d: "<<setw(12)<<d<<"next col"<<endl;

	//空格位置以#填充
	cout<<setfill('#');
	cout<<"i: "<<setw(12)<<i<<"next col"<<endl;
	cout<<"d: "<<setw(12)<<d<<"next col"<<endl;

	//恢复以空格填充
	cout<<setfill(' ');
}

7、默认情况下,输入操作符忽略空白,制表符,换行符,进纸和回车, 如果想要不忽略这些,需要声明cin<<noskipws, 恢复默认的忽略声明为 cin << skipws。

void  skipws_usage()
{
	char ch;
	cin >> noskipws;
	while (cin >> ch)
	{
		if (ch != '#')
		{
			cout<< ch;
		}
		else
			break;
	}

	cin>> skipws;
}

8、利用seekg,seekp,tellg等函数访问文件copyOut.txt,将文件中每行最后的位置输出到最后一行

abcd

efg

hi

j

代码:

int fstream_access_file_usage()
{
	fstream inOut("copyOut.txt", fstream::ate | fstream::in | fstream:: out); //fstream::ate  means fixed at the end of the file
	if (!inOut)
	{
		cerr<<"ERROR! Unable to open file" <<endl;
		return EXIT_FAILURE;
	}
	
	ifstream::pos_type end_mark = inOut.tellg();
	inOut.seekg(0, fstream::beg);
	int cnt = 0;
	string line;
	while (inOut && inOut.tellg() != end_mark && getline(inOut, line))
	{
		cnt+=line.size()+1;
		ifstream::pos_type mark = inOut.tellg();
		inOut.seekp(0, fstream::end);
		inOut<< cnt;
		if (mark != end_mark)
		{
			inOut<< " ";
		}
		inOut.seekg(mark);
	}
	inOut.clear();
	inOut.seekp(0, fstream::end);
	inOut<<"\n";
	return 0;
	
}

测试效果:

abcd
efg
hi
j
5 9 12 14



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值