hdu1282 回文数猜想 字符串操作
2015-05-02 10:58
267 查看
掌握逆序迭代器的使用以及stringstream的使用,这道题还是挺轻松的
使用sstream时要注意
流的操作,在遇到异常时会设置自身标志,如eof,fail,bad等等,这些标志中有一个为1,则流进入异常状态
这意味着,读到尾后,eof标志会被设置,此时流的状态不是good,而后想要再对他进行操作则必须清除状态,否则任何操作都是无效的(大概吧)。
具体见http://www.cplusplus.com/reference/ios/ios/good/
因此在本题中的使用应尽量使用函数,保证不会因为流读到文件尾而出问题。
具体见下例:
运行结果:
#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; }
运行结果:
相关文章推荐
- hdu1282 回文数猜想 字符串操作
- hdu-1282-回文数猜想( 存int类型操作 )
- HDU 1282 回文数猜想
- hdu 1282 回文数猜想
- HDU 1228 A + B 字符串操作(常规 & hash)
- hdu 1282 回文数猜想
- HDU 1282 回文数猜想(数学题)
- HDU 5058(set) 5059 (字符串操作)
- hdu 1282回文数猜想
- HDU 1282 回文数猜想
- 【HDU】1282 回文数猜想
- HDU 1282 回文数猜想(简单数学题)
- hdu 1282 回文数猜想
- HDU 1004 Let the Balloon Rise 字符串操作
- HDU 1282 回文数猜想
- HDU_1282回文数猜想
- 回文数猜想 HDU 1282
- HDU 1282 回文数猜想
- HDU 1020 Encoding 字符串操作
- hdu 1282 回文数猜想