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

C++ string 轉 int:C 風格 vs C++11 標準庫

     編輯:關於C++

C 風格

std::string str = "123";
int i = atoi(str.c_str()); // 需包含 <cstdlib>

C++11 標準庫(推薦)

#include <string>
std::string str = "123";
int i = std::stoi(str); // 拋出例外於無效輸入
long l = std::stol(str);
float f = std::stof(str);
double d = std::stod(str);

差異比較

特性atoistd::stoi
錯誤處理靜默回傳 0拋出 std::invalid_argument / std::out_of_range
支援進位制僅 10 進位可指定 base(2~36)
字串前導空白自動忽略自動忽略
標準CC++11

建議

現代 C++ 專案請統一使用 std::stoi 系列,獲得型別安全與明確錯誤報告。

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