プログラミングでは、文字列を整数に変換することが必要になることがよくあります。 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