溫馨提示×

c++ itoa函數(shù)處理負(fù)數(shù)的方法

c++
小樊
81
2024-09-13 01:17:02
欄目: 編程語言

在 C++ 中,itoa 函數(shù)不是標(biāo)準(zhǔn)庫函數(shù),但我們可以使用標(biāo)準(zhǔn)庫中的其他函數(shù)來實(shí)現(xiàn)類似的功能。對于負(fù)數(shù),我們需要先處理符號位,然后將負(fù)數(shù)轉(zhuǎn)換為正數(shù)進(jìn)行轉(zhuǎn)換。下面是一個簡單的示例:

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

std::string itoa(int value) {
    if (value == 0) {
        return "0";
    }

    std::string result;
    bool is_negative = false;

    if (value < 0) {
        is_negative = true;
        value = -value; // 將負(fù)數(shù)轉(zhuǎn)換為正數(shù)
    }

    while (value > 0) {
        int digit = value % 10;
        result += '0' + digit;
        value /= 10;
    }

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

    // 反轉(zhuǎn)字符串
    std::reverse(result.begin(), result.end());

    return result;
}

int main() {
    int num = -12345;
    std::string str = itoa(num);
    std::cout << "Converted string: "<< str<< std::endl;
    return 0;
}

這個示例中,我們首先檢查輸入值是否為負(fù)數(shù)。如果是負(fù)數(shù),我們將其轉(zhuǎn)換為正數(shù),并在轉(zhuǎn)換過程中記錄符號位。然后,我們將整數(shù)轉(zhuǎn)換為字符串,最后根據(jù)符號位添加負(fù)號。

0