簡體   English   中英

c ++ std :: string to boolean

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

我目前正在讀取帶有鍵/值對的ini文件。

isValid = true

獲取鍵/值對時,我需要將一個'true'字符串轉換為bool。 如果不使用boost,最好的方法是什么?

我知道我可以在值上進行字符串比較( "true""false" )但是我想在沒有ini文件中的字符串區分大小寫的情況下進行轉換。

謝謝

另一個解決方案是使用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");
#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
$ 

如果你不能使用boost,請嘗試strcasecmp

#include <cstring>

std::string value = "TrUe";

bool isTrue = (strcasecmp("true",value.c_str()) == 0);

通過迭代字符串並在carachters上調用tolower來小寫字符串,然后將其與"true""false" ,如果外殼是您唯一關心的問題。

for (std::string::iterator iter = myString.begin(); iter != myString.end(); iter++)
    *iter = tolower(*iter);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM