【发布时间】:2010-08-31 21:15:54
【问题描述】:
我目前正在读取带有键/值对的 ini 文件。即
isValid = true
获取键/值对时,我需要将字符串“true”转换为布尔值。如果不使用 boost,最好的方法是什么?
我知道我可以对值("true"、"false")进行字符串比较,但我希望在不区分 ini 文件中的字符串的情况下进行转换。
谢谢
【问题讨论】:
标签: c++
我目前正在读取带有键/值对的 ini 文件。即
isValid = true
获取键/值对时,我需要将字符串“true”转换为布尔值。如果不使用 boost,最好的方法是什么?
我知道我可以对值("true"、"false")进行字符串比较,但我希望在不区分 ini 文件中的字符串的情况下进行转换。
谢谢
【问题讨论】:
标签: c++
另一种解决方案是使用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");
【讨论】:
std::boolalpha
#include <algorithm>.
#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;
}
输入输出示例:
$ ./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
$
【讨论】:
strcasecmp 是不可移植的。奇怪的是,有些平台使用stricmp。
如果你不能使用 boost,试试strcasecmp:
#include <cstring>
std::string value = "TrUe";
bool isTrue = (strcasecmp("true",value.c_str()) == 0);
【讨论】:
strcasecmp 在 Windows 下不存在。
stricmp 更广泛地用于 C 样式字符串的不区分大小写的比较。
通过迭代字符串并在字符上调用tolower 来小写字符串,然后将其与"true" 或"false" 进行比较,如果您只关心大小写。
for (std::string::iterator iter = myString.begin(); iter != myString.end(); iter++)
*iter = tolower(*iter);
【讨论】:
关于 C++ 字符串大小写不敏感的字符串比较的建议可以在这里找到: Case insensitive string comparison in C++
【讨论】: