我目前正在读取带有键/值对的ini文件.即
isValid = true
Run Code Online (Sandbox Code Playgroud)
获取键/值对时,我需要将一个'true'字符串转换为bool.如果不使用boost,最好的方法是什么?
我知道我可以在值("true","false")上进行字符串比较但是我想在没有ini文件中的字符串区分大小写的情况下进行转换.
谢谢
Geo*_*che 30
另一个解决方案是使用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");
Run Code Online (Sandbox Code Playgroud)