c++

如何在c++中实现itoa函数的替代方案

小樊
87
2024-09-13 01:16:18
栏目: 编程语言

在C++中,itoa 函数并不是标准库的一部分,因此建议使用其他替代方法

方法1:使用std::to_string

#include<iostream>
#include<string>

int main() {
    int number = 42;
    std::string str_number = std::to_string(number);
    std::cout << "Number as string: "<< str_number<< std::endl;
    return 0;
}

方法2:使用std::ostringstream

#include<iostream>
#include <sstream>
#include<string>

int main() {
    int number = 42;
    std::ostringstream oss;
    oss<< number;
    std::string str_number = oss.str();
    std::cout << "Number as string: "<< str_number<< std::endl;
    return 0;
}

方法3:自定义itoa函数

#include<iostream>
#include<string>
#include<algorithm>

std::string itoa_custom(int value, int base = 10) {
    if (base < 2 || base > 36) {
        throw std::invalid_argument("Invalid base");
    }
    
    if (value == 0) {
        return "0";
    }

    char chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::string result;
    bool is_negative = value < 0;
    if (is_negative) {
        value = -value;
    }

    while (value != 0) {
        int remainder = value % base;
        result += chars[remainder];
        value /= base;
    }

    if (is_negative) {
        result += '-';
    }

    std::reverse(result.begin(), result.end());
    return result;
}

int main() {
    int number = 42;
    std::string str_number = itoa_custom(number);
    std::cout << "Number as string: "<< str_number<< std::endl;
    return 0;
}

这些方法都可以实现将整数转换为字符串。选择最适合你需求的方法。

0
看了该问题的人还看了