栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++内核格式化,看这一篇就够了

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++内核格式化,看这一篇就够了

内核格式化,看这一篇就够了

C++库提供了sstream族,他们使用相同的接口提供程序和string对象之间的I/O;可以使用与cout的ostream方法将格式化信息写入到string对象中,并使用istream方法来读取string对象中的信息;读取string对象中的格式化信息或将格式化信息写入string对象中被称为内核格式化。

头文件sstream定义了ostream的继承类ostringstream类(还有一个基于wostream的wostringstream类用于宽字符集。

ostringstream对象.str()—返回一个被初始化为缓冲区内容的字符串对象,使用str()方法可以”冻结“该对象,这样将不能再写入信息到该对象中。

istringstream类允许使用istream方法族读取istringstream对象中的数据,istringstream对象可以使用string对象进行初始化。

code:


// strout.cpp -- incore formatting (output)
#include 
#include 
#include 
int main()
{
	using namespace std;
	cout << "ostringstream**************************************************************" << endl;
	ostringstream outstr; // manages a string stream
	string hdisk;
	cout << "What's the name of your hard disk? ";
	getline(cin, hdisk);
	int cap;
	cout << "What's its capacity in GB? ";
	cin >> cap;
	// write formatted information to string stream
	outstr << "The hard disk " << hdisk << " has a capacity of "
		<< cap << " gigabytes.n";//此处并不会输出内容,此处只是将后面的内容插入到outstr流中
	string result = outstr.str(); // save result
	cout << result; // show contents 此处才会输出内容
	cout << "istringstream**************************************************************" << endl;
	string lit = "It was a dark and stormy day, and "
		" the full moon glowed brilliantly. ";
	istringstream instr(lit); // use buf for input
	string word;
	while (instr >> word) // read a word a time
		cout << word << endl;

	return 0;
}

运行结果:

ostringstream**************************************************************
What's the name of your hard disk? Jasmine
What's its capacity in GB? 900
The hard disk Jasmine has a capacity of 900 gigabytes.
istringstream**************************************************************
It
was
a
dark
and
stormy
day,
and
the
full
moon
glowed
brilliantly.

D:Prj_C++Self_32Incore_foamattingx64Debug_32Incore_foamatting.exe (进程 864)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/862630.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号