明天看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;
}
 



你可能感兴趣的:(明天看stringstream主要是相当与sprintf/sscanf函数的作用)