Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

c++ - std :: string格式如sprintf(std::string formatting like sprintf)

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

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

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...