C++ std::string to boolean
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3613284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c++ std::string to boolean
提问by Wesley
I am currently reading from an ini file with a key/value pair. i.e.
我目前正在使用键/值对读取 ini 文件。IE
isValid = true
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?
获取键/值对时,我需要将“true”字符串转换为布尔值。在不使用 boost 的情况下,最好的方法是什么?
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.
我知道我可以对值 ( "true"
, "false"
)进行字符串比较,但我想进行转换,而 ini 文件中的字符串不区分大小写。
Thanks
谢谢
回答by Georg Fritzsche
Another solution would be to use tolower()
to get a lower-case version of the string and then compare or use string-streams:
另一种解决方案是使用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");
回答by Wesley
#include <string>
#include <strings.h>
#include <cstdlib>
#include <iostream>
bool
string2bool (const std::string & v)
{
return !v.empty () &&
(strcasecmp (v.c_str (), "true") == 0 ||
atoi (v.c_str ()) != 0);
}
int
main ()
{
std::string s;
std::cout << "Please enter string: " << std::flush;
std::cin >> s;
std::cout << "This is " << (string2bool (s) ? "true" : "false") << std::endl;
}
An example input and output:
输入和输出示例:
$ ./test
Please enter string: 0
This is false
$ ./test
Please enter string: 1
This is true
$ ./test
Please enter string: 3
This is true
$ ./test
Please enter string: TRuE
This is true
$
回答by Uli Schlachter
Suggestions for case-insenstive string comparisions on C++ strings can be found here: Case insensitive string comparison in C++
可以在此处找到对 C++ 字符串 不区分大小写的字符串比较的建议:C++ 中不区分大小写的字符串比较
回答by Andre Holzner
If you can't use boost, try strcasecmp
:
如果您不能使用 boost,请尝试strcasecmp
:
#include <cstring>
std::string value = "TrUe";
bool isTrue = (strcasecmp("true",value.c_str()) == 0);
回答by zneak
Lowercase the string by iterating the string and calling tolower
on the carachters, then compare it to "true"
or "false"
, if casing is your only concern.
通过迭代字符串并调用tolower
carachters 来小写字符串,然后将其与"true"
或进行比较"false"
,如果您只关心大小写。
for (std::string::iterator iter = myString.begin(); iter != myString.end(); iter++)
*iter = tolower(*iter);