您的位置:首页 > 其它

hdu1282 回文数猜想 字符串操作

2015-05-02 10:58 267 查看
掌握逆序迭代器的使用以及stringstream的使用,这道题还是挺轻松的

#include<iostream>
#include<cstdio>
#include<cstring>
#include<sstream>
#include<queue>
#include<fstream>
#include<algorithm>
#include<map>
#include<vector>
#include<cmath>
#define CLR(x) memset(x,0,sizeof(x))
#define ll long long
using namespace std;
bool check(string a)
{
int i(0);
int j(a.size()-1);
while (i<j)
{
if (a[i]!=a[j])
return false;
i++;
j--;
}
return true;
}
int strtoint(const string& a)
{
stringstream tmp(a);
int result;
tmp>>result;
return result;
}
string inttostring(const int a)
{
stringstream tmp;
tmp<<a;
string res;
tmp>>res;
return res;
}
int main()
{
cin.sync_with_stdio(false);
string a;
while (cin>>a)
{
string res(a);
int count(0);
queue<string> result;
while (!check(a))
{
result.push(a);
count++;
string tp(a.rbegin(),a.rend());      //逆向迭代器作构造函数的参数
a=inttostring(strtoint(a)+strtoint(tp));
}
cout<<count<<endl;
while (!result.empty())
{
cout<<result.front()<<"--->";
result.pop();
}
cout<<a<<endl;
}
return 0;
}

使用sstream时要注意

流的操作,在遇到异常时会设置自身标志,如eof,fail,bad等等,这些标志中有一个为1,则流进入异常状态

这意味着,读到尾后,eof标志会被设置,此时流的状态不是good,而后想要再对他进行操作则必须清除状态,否则任何操作都是无效的(大概吧)。

具体见http://www.cplusplus.com/reference/ios/ios/good/

因此在本题中的使用应尽量使用函数,保证不会因为流读到文件尾而出问题。

具体见下例:

int main()
{
cin.sync_with_stdio(false);
stringstream sstream("1234aaaa");
string a;
string b;
sstream>>a;         //此时sstream读到文件尾,eof标识变为1
cout<<a<<endl;
sstream.str("aweawe");  //接下来对该流的操作都是无效的
sstream>>a;             //这个操作没有对a实际赋值,也没有改变sstream
sstream>>b;
cout<<a<<endl;
cout<<b<<endl;
return 0;
}

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: