在程式設計中,經常需要將字串轉換為整數。雖然 C 為此目的提供了 std::atoi 函數,但它不能優雅地處理轉換錯誤。為了解決這個問題,我們尋求允許錯誤處理的解決方案,類似 C# 的 Int32.TryParse。
一種有效的方法是使用 Boost 函式庫中的 lexical_cast 函式。它支援多種資料類型,如果轉換失敗可能會引發異常。這是一個範例:
#include
int main() {
std::string s;
std::cin >> s;
try {
int i = boost::lexical_cast(s);
// ...
} catch (...) {
// Handle error
}
}
如果Boost 不可用,則可以使用std::stringstream 和>> 運算子的組合:
#include
#include
#include
int main() {
std::string s;
std::cin >> s;
try {
std::stringstream ss(s);
int i;
if ((ss >> i).fail() || !(ss >> std::ws).eof()) {
throw std::bad_cast();
}
// ...
} catch (...) {
// Handle error
}
}
作為最後的替代方案,可以創建 Boost 的 lexical_cast 函數的「假」版本:
#include
#include
#include
template
T lexical_cast(const std::string& s) {
std::stringstream ss(s);
T result;
if ((ss >> result).fail() || !(ss >> std::ws).eof()) {
throw std::bad_cast();
}
return result;
}
int main() {
std::string s;
std::cin >> s;
try {
int i = lexical_cast(s);
// ...
} catch (...) {
// Handle error
}
}
如果需要無拋出版本,捕獲適當的異常並返回指示成功或失敗的布爾值:
template
bool lexical_cast(const std::string& s, T& t) {
try {
t = lexical_cast(s);
return true;
} catch (const std::bad_cast& e) {
return false;
}
}
int main() {
std::string s;
std::cin >> s;
int i;
if (!lexical_cast(s, i)) {
std::cout
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3