我必须格式化 std::string
与 sprintf
并将其发送到文件流中。我怎样才能做到这一点?
最佳答案
您不能直接执行此操作,因为您没有对底层缓冲区的写访问权限(直到 C++11;请参阅 Dietrich Epp 的 comment )。您必须先在 c 字符串中执行此操作,然后将其复制到 std::string 中:
char buff[100];
snprintf(buff, sizeof(buff), "%s", "Hello");
std::string buffAsStdStr = buff;
但我不确定为什么不只使用字符串流?我假设你有特定的理由不只是这样做:
std::ostringstream stringStream;
stringStream << "Hello";
std::string copyOfStr = stringStream.str();
关于c++ - std::string 格式,如 sprintf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2342162/