std::string formatting like sprintf

前端 未结 30 2572
野趣味
野趣味 2020-11-22 04:42

I have to format std::string with sprintf and send it into file stream. How can I do this?

30条回答
  •  情深已故
    2020-11-22 05:09

    You can't do it directly, because you don't have write access to the underlying buffer (until C++11; see Dietrich Epp's comment). You'll have to do it first in a c-string, then copy it into a std::string:

      char buff[100];
      snprintf(buff, sizeof(buff), "%s", "Hello");
      std::string buffAsStdStr = buff;
    

    But I'm not sure why you wouldn't just use a string stream? I'm assuming you have specific reasons to not just do this:

      std::ostringstream stringStream;
      stringStream << "Hello";
      std::string copyOfStr = stringStream.str();
    

提交回复
热议问题