使用 C 中的錯誤處理將字串轉換為 int
將字串轉換為整數是程式設計中的常見任務。但是,在某些情況下,字串值可能無法成功轉換為整數。在這種情況下,優雅地處理轉換失敗至關重要。
boost::lexical_cast
將字串轉換為 int 時出現錯誤的最直接方法之一處理方法是使用 boost::lexical_cast 函數。如果轉換無法繼續,則該函數會拋出異常,允許我們捕獲它並做出適當的響應。
#include
int main() {
std::string s;
std::cin >> s;
try {
int i = boost::lexical_cast(s);
} catch (...) {
// Handle the conversion failure
}
}
使用標準函式庫函數
不使用 boost 的另一種方法是利用標準函式庫函數,例如 std::stringstream 和 std::bad_cast。
#include
#include
int main() {
std::string s;
std::cin >> s;
std::stringstream ss(s);
int i;
if ((ss >> i).fail() || !(ss >> std::ws).eof()) {
throw std::bad_cast();
}
}
自訂函數
為了實現可自訂性,您可以建立一個模擬 boost::lexical_cast 功能並管理轉換失敗的函數。
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;
}
非拋出版本
如果您希望避免拋出異常,您可以通過捕獲異常並返回失敗來創建上述函數的無拋出版本Indicator.
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;
}
}
使用這些方法,您可以有效地將字串轉換為整數,同時處理潛在的轉換失敗。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3