c++ std::string から boolean へ 質問する

c++ std::string から boolean へ 質問する

私は現在、キー/値のペアを持つiniファイルから読み取っています。つまり

isValid = true

キー/値のペアを取得するときに、「true」の文字列をブール値に変換する必要があります。boost を使用せずにこれを行う最善の方法は何でしょうか?

値 ( "true""false") で文字列を比較できることはわかっていますが、ini ファイル内の文字列の大文字と小文字を区別せずに変換を実行したいと思います。

ありがとう

ベストアンサー1

tolower()別の解決策としては、を使用して文字列の小文字バージョンを取得し、比較したり文字列ストリームを使用したりすることが考えられます。

#include <sstream>
#include <string>
#include <iomanip>
#include <algorithm>
#include <cctype>

bool to_bool(std::string str) {
    std::transform(str.begin(), str.end(), str.begin(), ::tolower);
    std::istringstream is(str);
    bool b;
    is >> std::boolalpha >> b;
    return b;
}

// ...
bool b = to_bool("tRuE");

おすすめ記事