首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C++ 字符串轉整數:atoi vs stoi 完整指南

     編輯:C++ 入門

C/C++ 中將 std::string 轉為整數的標準方法演進與最佳實踐。

C 風格:atoi / strtol

std::string s = "12345";
int val = atoi(s.c_str());           // 簡單但無錯誤檢測
long val2 = strtol(s.c_str(), nullptr, 10); // 可檢測錯誤、支援進制

缺點:atoi 非法輸入行為未定義(通常返回 0),無法區分「輸入 0」與「轉換失敗」;需手動管理 char*。

C++11 標準:std::stoi 系列

std::string s = "12345";
int val = std::stoi(s);              // 拋出異常於錯誤
long val2 = std::stol(s);
long long val3 = std::stoll(s);
float f = std::stof(s);
double d = std::stod(s);

優點:

  • 直接接受 std::string,無需 .c_str()
  • 異常機制明確區分轉換失敗(std::invalid_argument、std::out_of_range)
  • 支援 size_t* idx 參數獲取解析字符數
  • 支援基數(base 參數,默認 10)

異常處理範例

std::string s = "123abc";
try {
    size_t pos;
    int val = std::stoi(s, &pos);  // val=123, pos=3
    // 可檢查 pos == s.size() 判斷是否完全解析
} catch (const std::invalid_argument& e) {
    // 無數字開頭
} catch (const std::out_of_range& e) {
    // 超出 int 範圍
}

C++17 新增:std::from_chars(高性能、無異常)

#include <charconv>
std::string s = "12345";
int val;
auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), val);
if (ec == std::errc()) {
    // 成功,ptr 指向首個未解析字符
} else if (ec == std::errc::invalid_argument) {
    // 格式錯誤
} else if (ec == std::errc::result_out_of_range) {
    // 溢出
}

優勢:無異常開銷、無區域化依賴、可直接操作字符指針、性能極高(適合熱路徑解析)。

對比總結

函數標準錯誤處理性能推薦場景
atoiC無(UB)高極簡代碼、確信輸入合法
strtolCerrno/指針高C 代碼、需檢測錯誤
stoi/stol/...C++11異常中(異常開銷)通用 C++ 代碼、異常安全環境
from_charsC++17error_code極高高性能解析、無異常環境、嵌入式

最佳實踐建議

  1. 現代 C++(C++17+)首選 std::from_chars
  2. C++11/14 環境用 std::stoi 並捕獲異常
  3. 避免 atoi,除非極度確定輸入合法且不關心錯誤
  4. 解析用戶輸入/網絡數據時,必須檢查完全解析(pos == size() 或 ptr == end)

正確選擇轉換函數,能讓代碼更安全、高效、可維護。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved