How to convert a number to string and vice versa in C++

前端 未结 5 1082
鱼传尺愫
鱼传尺愫 2020-11-22 03:36

Since this question gets asked about every week, this FAQ might help a lot of users.

  • How to convert an integer to a string in C++

  • how to con

5条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 04:14

    I stole this convienent class from somewhere here at StackOverflow to convert anything streamable to a string:

    // make_string
    class make_string {
    public:
      template 
      make_string& operator<<( T const & val ) {
        buffer_ << val;
        return *this;
      }
      operator std::string() const {
        return buffer_.str();
      }
    private:
      std::ostringstream buffer_;
    };
    

    And then you use it as;

    string str = make_string() << 6 << 8 << "hello";
    

    Quite nifty!

    Also I use this function to convert strings to anything streamable, althrough its not very safe if you try to parse a string not containing a number; (and its not as clever as the last one either)

    // parse_string
    template 
    RETURN_TYPE parse_string(const STRING_TYPE& str) {
      std::stringstream buf;
      buf << str;
      RETURN_TYPE val;
      buf >> val;
      return val;
    }
    

    Use as:

    int x = parse_string("78");
    

    You might also want versions for wstrings.

提交回复
热议问题