C++ 流的使用 Part II - string stream 和 流的格式化输出

字符串流的使用。

继承图


C++ 流的使用 Part II - string stream 和 流的格式化输出_第1张图片





示例代码:istringstream


#include <iostream>
#include <string>
#include <sstream>

using namespace std;


void main()
{
	string strTest("12 45.67 ABCD");
	int i = 0;
	double d = 0;
	string str = "";


	istringstream s(strTest);

	s >> i >> d >> str ;    // the same as atof() and atoi(), atof() atoi() with higher performance

	cout << "int = " << i << endl;
	cout << "double = " << d << endl;
	cout << "string = " << str << endl;

	cin >> i;

}

测试结果:




示例代码:ostringstream

#include <iostream>
#include <string>
#include <sstream>

using namespace std;


void main()
{
	int i = 123;
	double d = 4.56;
	string str = "ABCDE";

	ostringstream os;


	os << "int =" << i << endl;
	os << "double =" << d << endl;
	os << "string =" << str << endl;

	string result = os.str();

	cout << "Result : " << endl << result << endl;

	cin >> i;

}

C++ 流的使用 Part II - string stream 和 流的格式化输出_第2张图片




输出流的格式化


开关标志

ios::unitbuf  :  单元缓冲区每次插入后立即刷新(马上进行输出)。



ios::showpos  :  在数字正数前加 "+"。


ios::skipws   : 输入流中忽略空格。


ios::showpoint   : 显示浮点值的小数点。



代码示例 输出格式化数字:


#include <iostream>
#include <string>
#include <sstream>

using namespace std;


void main()
{
	int i = 123;
	double d = 4.56;
	string str = "ABCDE";

	ostringstream os;


	os << "int =" << i << endl;
	os << "double =" << d << endl;
	os << "string =" << str << endl;

	string result = os.str();

	cout << "Result : " << endl << result << endl;

	cin >> i;

}


测试结果:

C++ 流的使用 Part II - string stream 和 流的格式化输出_第3张图片




格式化域  ios::basefield

ios::hex : 输出 16 进制


ios::dec : 输出 10 进制


ios::oct : 输出 8 进制

ios::scientific : 输出科学计数法


ios::fixed : 以固定格式显示浮点数,与 setprecision(n) 连用。


ios::left  : 使输出左对齐。
ios::right : 使输出右对齐。


ios::width()   : 返回当前设置的宽度
ios::width(n)  : 设置当前的宽度


ios::fill()      : 返回当前设置填充字符
ios::fill(char)  : 设置当前的填充字符


ios::precision()   : 返回当前设置浮点数精度
ios::precision(n)  : 设置当前的浮点数精度



代码示例 输出控制:


#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

void main()
{
    int i = 100;
	double d = 123.456;
	string str = "ABCD";

	cout << "i = " << i <<endl;
	cout << "d = " << d <<endl;

	cout << "i (hex) = " << hex << i << endl;
	cout << "i (dec) = " << dec << i << endl;
	cout << "i (oct) = " << oct << i << endl;

	cout << "d (scientific) = " << scientific << d << endl;
	cout << "d (fixed) = " << fixed << setprecision(6) << d << endl;  // total has 6 number after the point

	cout.fill('#');
	cout.setf(ios::left);
	cout.width(10);
	cout<< i  << "   the fill chart is " << cout.fill() << endl;

	cout.fill('*');
	cout.setf(ios::right);
	cout.width(10);
	cout<<  i << "   the fill chart is " << cout.fill() << endl;

	cout.fill('-');
	cout.setf(ios::right);
	cout.width(10);
	cout<<  str << "   the fill chart is " << cout.fill() << endl;

	cin >> i;
}


测试结果:


C++ 流的使用 Part II - string stream 和 流的格式化输出_第4张图片





你可能感兴趣的:(C++ 流的使用 Part II - string stream 和 流的格式化输出)