首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ string 存儲數字如何進行加減運算:類型轉換全攻略

     編輯:程式設計綜合問答

核心方法

#include 
#include    // atoi, strtol
#include    // stringstream
#include  // stoi, stod (C++11)

std::string s = "12345";

// 1. C++11 標準庫 (推薦)
int i = std::stoi(s);           // 拋出 invalid_argument / out_of_range
long l = std::stol(s);
double d = std::stod(s);

// 2. C 風格 (不拋異常,錯誤返回 0)
int i2 = std::atoi(s.c_str());
long l2 = std::strtol(s.c_str(), nullptr, 10);

// 3. stringstream (舊標準通用)
std::stringstream ss(s);
int i3; ss >> i3;

// 運算後轉回 string
std::string result = std::to_string(i + 10);  // C++11
// 或
char buf[32]; std::sprintf(buf, "%d", i + 10); std::string result2(buf);

完整封裝示例

template <typename T>
T str_to_num(const std::string& s) {
    std::stringstream ss(s);
    T val; ss >> val;
    if (ss.fail() || !ss.eof()) throw std::runtime_error("Invalid number: " + s);
    return val;
}

std::string num_to_str(auto val) { return std::to_string(val); } // C++20
// C++17: template std::string num_to_str(T val) { return std::to_string(val); }

注意事項

  • atoi 無錯誤檢測,"abc" 返回 0,生產環境禁用。
  • stoi 遇非數字拋異常,需 try-catch。
  • 大數字/高精度用 boost::multiprecision::cpp_int 或 long double。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved