Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have to format std::string with sprintf and send it into file stream.

(我必须用sprintf格式化std::string并将其发送到文件流中。)

How can I do this?

(我怎样才能做到这一点?)

  ask by Max Frai translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
289 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 ).

(您不能直接执行此操作,因为您没有对基础缓冲区的写访问权限(直到C ++ 11;请参见Dietrich Epp的注释 )。)

You'll have to do it first in a c-string, then copy it into a std::string:

(您必须首先在c字符串中执行此操作,然后将其复制到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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...