c ++ std :: string to boolean [英] c++ std::string to boolean

查看:424
本文介绍了c ++ std :: string to boolean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从带有键/值对的ini文件中读取。即

I am currently reading from an ini file with a key/value pair. i.e.

isValid = true

当获取键/值对时,我需要将一个true的字符串转换为bool。

When get the key/value pair I need to convert a string of 'true' to a bool. Without using boost what would be the best way to do this?

我知道我可以这样做一个字符串比较的值(truefalse)但我想做转换,而不是ini文件中的字符串区分大小写。

I know I can so a string compare on the value ("true", "false") but I would like to do the conversion without having the string in the ini file be case sensitive.

感谢

推荐答案

另一个解决方案是使用 tolower 获取字符串的小写版本,然后比较或使用字符串流:

Another solution would be to use tolower() to get a lower-case version of the string and then compare or use string-streams:

#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");

这篇关于c ++ std :: string to boolean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆