明天看stringstream主要是相当与sprintf/sscanf函数的作用

明天看stringstream主要是相当与sprintf/sscanf函数的作用
C_Style
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int get_next(int x)
{
    char s[10];
    sprintf(s, "%d", x);
    int n = strlen(s);
    for(int i = 0; i < n; ++i)
        for(int j = i+1; j < n; ++j)
            if(s[i] > s[j])
            {
                char t = s[i];
                s[i] = s[j];
                s[j] = t;
            }
    int b;
    sscanf(s, "%d", &b);
//字符串反转
    for(int i = 0; i < n/2; ++i)
    {
        char t = s[i];
        s[i] = s[n-i-1];
        s[n-i-1] = t;
    }
    int a;
    sscanf(s, "%d", &a);
    return a-b;
}
int num[2000], count;
int main()
{
    cin >> num[0];
    cout << num[0];
    count = 1;
    while(1)
    {
        //生成并输出下一个数
        num[count] = get_next(num[count-1]);
        cout << " -> " << num[count];
        //在数组n中寻找新生成的书
        int found = 0;
        for(int i = 0; i < count; ++i)
            if(num[i] == num[count])
            {
                found = 1;
                break;
            }//如果找到,推出循环
        if(found)break;
        count++;
    }
    cout << endl;
    return 0;
}


C++_Style
#include<iostream>
#include<sstream>
using namespace std;
 
int get_next(int x)
{
    stringstream stream;
    string s;
    stream << x;
    stream >> s;
    for(string::size_type i  = 0; i != s.size(); ++i)
        for(string::size_type j = i + 1; j != s.size(); ++j)
            if(s[i] > s[j])
            {
                char t = s[i];
                s[i] = s[j];
                s[j] = t;
            }
    stream.clear();//多次转换前,必须清楚stream
    stream << s;
    stream >> x;
//字符串反串
    for(string::size_type i = 0; i < s.size()/2; ++i)
    {
        char t = s[i];
        s[i] = s[s.size()-i-1];
        s[s.size()-i-1] = t;
    }
    int y;
    stream.clear();//多次转换前,必须清楚stream
    stream << s;
    stream >> y;
    return y - x;
}
int num[2000], count;
int main()
{
    cin >> num[0];
    cout << num[0];
    count = 1;
    while(1)
    {
//生成并输出下一个数
        num[count] = get_next(num[count-1]);
        cout << " -> " << num[count];
//在数组n中寻找新生成的数
        int found = 0;
        for(int i  = 0; i < count; ++i)
            if(num[i] == num[count])
            {
                found = 1;
                break;
            }
        if(found) break;
        count++;
    }
    cout << endl;
    return 0;
}
 



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值