hdu1282 回文数猜想 字符串操作

掌握逆序迭代器的使用以及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;
}

运行结果:
这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值