【问题标题】:c++ std::string to booleanc++ std::string 到布尔值
【发布时间】:2010-08-31 21:15:54
【问题描述】:

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

isValid = true

获取键/值对时,我需要将字符串“true”转换为布尔值。如果不使用 boost,最好的方法是什么?

我知道我可以对值("true""false")进行字符串比较,但我希望在不区分 ini 文件中的字符串的情况下进行转换。

谢谢

【问题讨论】:

    标签: c++


    【解决方案1】:

    另一种解决方案是使用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");
    

    【讨论】:

    • +1 好答案 + 另一个 1 因为我不知道 boolalpha。请注意, boost::lexical_cast (也一样)对大小写也不是很宽容
    • 这真的很酷...我以前不知道std::boolalpha
    • 我尝试使用它,但它说转换不是标准的一部分。我加入了 我错过了什么?
    • @Wesley: #include &lt;algorithm&gt;.
    【解决方案2】:
    #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
    【解决方案3】:

    如果你不能使用 boost,试试strcasecmp:

    #include <cstring>
    
    std::string value = "TrUe";
    
    bool isTrue = (strcasecmp("true",value.c_str()) == 0);
    

    【讨论】:

    • strcasecmp 在 Windows 下不存在。
    • 哦,来吧!听起来 Boost 是比较字符串的唯一方法 :-) 确实有比进行词法转换更简单有效的方法。尤其是当您确切地知道自己在做什么而不是创建通用的多合一转换库时。
    • @zneak - 虽然 Windows 有“stricmp” (msdn.microsoft.com/en-us/library/k59z8dwe%28v=VS.80%29.aspx)
    • strcmpi 是 POSIX 标准,具有愚蠢的弃用,但在 Visual Studio 中仍然有效。
    • stricmp 更广泛地用于 C 样式字符串的不区分大小写的比较。
    【解决方案4】:

    通过迭代字符串并在字符上调用tolower 来小写字符串,然后将其与"true""false" 进行比较,如果您只关心大小写。

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

    【讨论】:

    • tolower() 作用于单个字符,c_str() 返回指向不得修改的字符串的指针。所以这个想法实际上是有害的。
    • @Uli Schlanchter 我到底是从哪里得到它在弦乐上工作的想法?谢谢你的收获。
    【解决方案5】:

    关于 C++ 字符串大小写不敏感的字符串比较的建议可以在这里找到: Case insensitive string comparison in C++

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 2017-09-22
      • 1970-01-01
      相关资源
      最近更新 更多