【问题标题】:Concatenate a string and a boolean in C++?在 C++ 中连接字符串和布尔值?
【发布时间】:2012-08-10 19:08:48
【问题描述】:

我想做如下的事情:

bool b = ...
string s = "Value of bool is: " + b ? "f" : "d";

我见过的所有示例都使用cout,但我不想打印字符串;把它存起来。

我该怎么做?如果可能的话,我想要一个分配给char * 和一个分配给std::string 的示例。

【问题讨论】:

    标签: c++ string char boolean concatenation


    【解决方案1】:

    如果你的编译器足够新,它应该有std::to_string:

    string s = "Value of bool is: " + std::to_string(b);
    

    这当然会将"1"(对于true)或"0"(对于false)附加到您的字符串,而不是您想要的"f""d"。原因是std::to_string 没有采用bool 类型的重载,因此编译器将其转换为整数值。

    你当然可以分两步做,首先声明字符串然后附加值:

    string s = "Value of bool is: ";
    s += b ? "f" : "d";
    

    或者像现在一样做,但明确地将第二个创建为std::string

    string s = "Value of bool is: " + std::string(b ? "f" : "d");
    

    编辑:如何从std::string获取char指针

    这是通过std::string::c_str 方法完成的。但正如 Pete Becker 所指出的,您必须小心如何使用此指针,因为它指向字符串对象内的数据。如果对象被销毁,数据也会被销毁,如果保存,指针现在将无效。

    【讨论】:

    • 分配给char * 怎么样?我正在尝试在方法签名中调用一个需要它的函数。
    • @asdf4lyfe 在字符串上调用c_str(),它会给你一个const char*
    • 谢谢! @Joachim-Pileborg,如果您可以将其编辑为很好的答案。
    • @Peter - 对,但要注意终身问题。返回的 char* 指向字符串对象内部的内存,如果字符串对象被修改或销毁,它就会消失。
    【解决方案2】:

    使用ostringstream:

    std::ostringstream s;
    s << "Value of bool is: " << b;
    std::string str(s.str());
    

    您可以使用std::boolalpha 来拥有"true""false" 而不是int 表示:

    s << std::boolalpha << "Value of bool is: " << b;
    

    注意贴出的代码几乎是正确的(不可能+两个char[]):

    std::string s = std::string("Value of bool is: ") + (b ? "t" : "f");
    

    要分配给char[],您可以使用snprintf()

    char buf[1024];
    std::snprintf(buf, 1024, "Value of bool is: %c", b ? 't' : 'f');
    

    或者只是std::string::c_str()

    【讨论】:

      【解决方案3】:

      足够简单:

      std::string s = std::string("Value of bool is: ") + (b ? "f" : "d");
      

      【讨论】:

        【解决方案4】:

        我会使用std::stringstream:

        std::stringstream ss;
        ss << s << (b ? "f" : "d");
        std::string resulting_string = ss.str();
        

        stringstream reference

        【讨论】:

          【解决方案5】:

          分两步进行操作:

          bool b = ...
          string s = "Value of bool is: ";
          s+= b ? "f" : "d";
          

          这是必要的,否则您将尝试将两个 const char * 相加,这是不允许的;这样一来,您就可以依赖 += 运算符的重载来处理 std::string 和 C 字符串。

          【讨论】:

            【解决方案6】:

            简单点:

            bool b = ...
            string s = "Value of bool is: ";
            if (b)
              s += "f";
            else
              s += "d";
            

            【讨论】:

              【解决方案7】:

              封装:

              std::string toString(const bool value)
              {
                  return value ? "true" : "false";
              }
              

              然后:

              std::string text = "Value of bool is: " + toString(b);
              

              【讨论】:

                【解决方案8】:

                你也可以使用 strcat()

                char s[80];
                strcpy(s, "Value of bool is ");
                strcat(s, b?"f":"d");
                

                【讨论】:

                  【解决方案9】:

                  对于这个简单的用例,只需将一个字符串附加到另一个字符串:

                  std::string text = std::string("Value of bool is: ").append( value? "true" : "false" ); 
                  

                  现在,对于更通用的解决方案,您可以创建一个字符串构建器类:

                  class make_string {
                     std::ostringstream st;
                     template <typename T>
                     make_string& operator()( T const & v ) {
                         st << v;
                     }
                     operator std::string() {
                         return st.str();
                     }
                  };
                  

                  可以轻松扩展以支持操纵器(添加几个额外的重载),但这足以满足大多数基本用途。然后将其用作:

                  std::string msg = make_string() << "Value of bool is " << (value?"true":"false");
                  

                  (同样,在这种特殊情况下,它是矫枉过正的,但如果你想组成一个更复杂的字符串,这将是有帮助的)。

                  【讨论】:

                    猜你喜欢
                    • 2015-02-07
                    • 1970-01-01
                    • 1970-01-01
                    • 2013-06-13
                    • 2019-05-03
                    • 2018-09-10
                    • 2019-10-15
                    • 2018-04-04
                    • 2013-02-08
                    相关资源
                    最近更新 更多