c++ std::string to boolean

前端 未结 5 850
天命终不由人
天命终不由人 2021-01-01 13:16

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

isValid = true

When get the key/value pair I need to convert a string

相关标签:
5条回答
  • 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.

    for (std::string::iterator iter = myString.begin(); iter != myString.end(); iter++)
        *iter = tolower(*iter);
    
    0 讨论(0)
  • 2021-01-01 14:03

    Suggestions for case-insenstive string comparisions on C++ strings can be found here: Case insensitive string comparison in C++

    0 讨论(0)
  • 2021-01-01 14:08

    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");
    
    0 讨论(0)
  • 2021-01-01 14:11
    #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
    $ 
    
    0 讨论(0)
  • 2021-01-01 14:13

    If you can't use boost, try strcasecmp:

    #include <cstring>
    
    std::string value = "TrUe";
    
    bool isTrue = (strcasecmp("true",value.c_str()) == 0);
    
    0 讨论(0)
提交回复
热议问题