手写to_string()

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>

using namespace std;

string my_tostring(int x)
{
    vector<char> tmp;
    bool flag = false; // 判断是否为负数
    if(x < 0)
    {
        x *= -1;
        flag = true;
    }
    while (x)
    {
        tmp.push_back(x % 10 + '0');
        x /= 10;
    }
    if(flag) tmp.push_back('-');
    reverse(tmp.begin(), tmp.end());

    string s = "";
    for (auto c : tmp)
        s += c;
    return s;
}

int main()
{
    int n;
    cin >> n;

    string s = my_tostring(n);

    cout << s;

    system("pause");
    return 0;
}
posted @ 2022-10-09 15:25  r涤生  阅读(33)  评论(0编辑  收藏  举报