以下是一种实现方式:

#include <string>

std::string intToString(int num) {
    std::string str;
    bool negative = false;
    
    if (num == 0) {
        return "0";
    }
    else if (num < 0) {
        negative = true;
        num = -num;
    }
    
    while (num > 0) {
        char digit = '0' + (num % 10);
        str = digit + str;
        num /= 10;
    }
    
    if (negative) {
        str = '-' + str;
    }
    
    return str;
}

该函数先处理特殊情况,即输入为0或负数时,然后利用循环将每一位数字转为字符,并将其拼接到字符串的头部。最后,如果输入为负数,再在字符串头部添加一个负号。

使用示例:

int num = 12345;
std::string str = intToString(num);
std::cout << str << std::endl; // 输出 "12345"

num = -6789;
str = intToString(num);
std::cout << str << std::endl; // 输出 "-6789"
用c++编写函数将正整形转为字符串不能使用to_string

原文地址: https://www.cveoy.top/t/topic/bY8w 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录