萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C++ 實現 int 與 string 相互轉換的最佳實踐

為什麼需要封裝轉換函數?

在 C++ 開發中,整數與字符串的相互轉換是高頻操作。標準庫雖提供了多種方式,但直接調用往往代碼冗長且易出錯。將轉換邏輯封裝為通用函數,可提高代碼復用性、可讀性與維護性。

int 轉 string:使用 stringstream

std::stringstream 是類型安全的流操作類,支持 `<<` 運算符將數值格式化為字符串。

#include 
#include 

std::string intToString(int num) {
    std::stringstream ss;
    ss << num;
    return ss.str();
}

優點:類型安全、支持格式控制(如進制、精度)、無緩衝區溢出風險。

string 轉 int:推薦使用 std::stoi (C++11)

現代 C++ 提供了 std::stoi,比舊式 atoi 更安全,能拋出異常處理錯誤輸入。

#include 

int stringToInt(const std::string& str) {
    try {
        return std::stoi(str);
    } catch (const std::exception& e) {
        // 處理轉換失敗:拋出自定義異常、返回默認值或記錄日誌
        return 0; // 示例返回 0
    }
}

注意:atoi 遇到非數字字符會靜默停止,返回 0 且無法區分「轉換結果為 0」與「轉換失敗」,不推薦在新代碼中使用。

完整示例程序

#include 
#include 
#include 

std::string intToString(int num) {
    std::stringstream ss;
    ss << num;
    return ss.str();
}

int stringToInt(const std::string& str) {
    try {
        return std::stoi(str);
    } catch (...) {
        return 0; // 簡化錯誤處理
    }
}

int main() {
    // int -> string
    std::string str1 = intToString(321);
    std::cout << "str1 = " << str1 << std::endl; // 輸出: str1 = 321

    // string -> int
    std::string str2 = "456";
    int m = stringToInt(str2);
    std::cout << "m = " << m << std::endl; // 輸出: m = 456

    // 錯誤輸入測試
    std::string invalid = "abc";
    std::cout << "invalid -> " << stringToInt(invalid) << std::endl; // 輸出: 0

    return 0;
}

進階提示

  • 性能敏感場景:可使用 to_chars/from_chars (C++17) 避免流對象開銷。
  • 其他進制:stringstream 配合 std::hex/std::oct;stoi 第三個參數指定基數。
  • 浮點數轉換:同理使用 std::stod、std::to_string (C++11) 或 stringstream。
copyright © 萬盛學電腦網 all rights reserved