HDU 1088 (模拟)使用<sstream>模版库

#include <sstream>

你的编译器支持<sstream>吗?

<sstream>库是最近才被列入C++标准的。(不要把<sstream>与标准发布前被删掉的<strstream>弄混了。)因此,老一点的编译器,如GCC2.95,并不支持它。如果你恰好正在使用这样的编译器而又想使用<sstream>的话,就要先对它进行升级更新。

<sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本。简单起见,我主要以stringstream为中心,因为每个转换都要涉及到输入和输出操作。

注意,<sstream>使用string对象来代替字符数组。这样可以避免缓冲区溢出的危险。而且,传入参数和目标对象的类型被自动推导出来,即使使用了不正确的格式化符也没有危险。

string到int的转换

string result=”10000”;
int n=0;
stream<<result;
stream>>n;//n等于10000

重复利用stringstream对象

如果你打算在多次转换中使用同一个stringstream对象,记住再每次转换前要使用clear()方法;

在多次转换中重复使用同一个stringstream(而不是每次都创建一个新的对象)对象最大的好处在于效率。stringstream对象的构造和析构函数通常是非常耗费CPU时间的。

代码参考了别人的,然后自己学习了下stringstream:

CODE:

/*
 *problem ID: HDU 1088
 *Author ID: fuqiang11
 *TIME: 2013-07-16 15:47:10 
*/

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <sstream>  //添加头文件 

using namespace std;
string br = "--------------------------------------------------------------------------------";
int main()
{
	string line;
	
	int count = 0;
	while(getline(cin,line))
	{
		stringstream stream(line); //初始化line为stringstream类型 
		string word;    //接受一个一个的单词 
		while(stream>>word)   //从stringstream流输入到word 
		{
//			cout<<count;
			if( word == "<br>" )
			{
				count = 0;
				cout<<endl;
				continue;
			}else 
			if( word == "<hr>")
			{
				if(count != 0)
				cout<<endl<<br<<endl;
				else
					cout<<br<<endl;
				count = 0;
				continue;
			}
			if(count == 0)
			{
				count = word.size();
				cout<<word;
				continue;
			}else 
			if(count + word.size() + 1 > 80)
			{
				count = word.size();  //size
				cout<<endl<<word;
				continue;
			}
			count += (word.size() + 1);
			cout<<" "<<word;
		}
	}
	cout<<endl;
}
关于stringtream的简单实用:

#include <sstream>
#include <iostream> 

int main()
{
    std::stringstream stream;
    char result[8] ;
    stream << 8888; //向stream中插入8888
    stream >> result; //抽取stream中的值到result
    std::cout << result << std::endl; // 屏幕显示 "8888"
} 

关于清空内容:

.clear()是清空标志位 
.str() 是清内容
.str("")才是真正的清内容,采用断点调试,
stringstream stream;//只申明什么都不做
的执行结果和
stringstream stream;
stream<<"sfsfs";
stream.str("");
执行结果是一样的是一样的(断点后看结果都是有很多的“0X00000‘指向错误的指针’”)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值