在C++項目中,有多種方法可以將字符串轉(zhuǎn)換為數(shù)字
使用C++標(biāo)準(zhǔn)庫中的函數(shù):
std::stoi
:將字符串轉(zhuǎn)換為int。std::stol
:將字符串轉(zhuǎn)換為long。std::stoll
:將字符串轉(zhuǎn)換為long long。std::stoul
:將字符串轉(zhuǎn)換為unsigned long。std::stoull
:將字符串轉(zhuǎn)換為unsigned long long。std::stof
:將字符串轉(zhuǎn)換為float。std::stod
:將字符串轉(zhuǎn)換為double。std::stold
:將字符串轉(zhuǎn)換為long double。示例:
#include<iostream>
#include<string>
#include <stdexcept>
int main() {
std::string str_num = "42";
try {
int num = std::stoi(str_num);
std::cout << "The number is: "<< num<< std::endl;
} catch (const std::invalid_argument& e) {
std::cerr << "Invalid argument: " << e.what()<< std::endl;
} catch (const std::out_of_range& e) {
std::cerr << "Out of range: " << e.what()<< std::endl;
}
return 0;
}
使用C語言風(fēng)格的函數(shù)(不推薦):
atoi
:將字符串轉(zhuǎn)換為int。atol
:將字符串轉(zhuǎn)換為long。atoll
:將字符串轉(zhuǎn)換為long long。atof
:將字符串轉(zhuǎn)換為double。示例:
#include<iostream>
#include <cstdlib>
#include<string>
int main() {
std::string str_num = "42";
int num = atoi(str_num.c_str());
std::cout << "The number is: "<< num<< std::endl;
return 0;
}
使用自定義函數(shù):
如果上述方法無法滿足需求,可以編寫自定義函數(shù)來實現(xiàn)字符串到數(shù)字的轉(zhuǎn)換。這可能涉及到處理特殊情況、錯誤檢查等。
在選擇合適的字符串轉(zhuǎn)數(shù)函數(shù)時,請考慮以下因素:
根據(jù)項目需求和場景,選擇最適合的字符串轉(zhuǎn)數(shù)函數(shù)。