输出到字符串的 cout 相当于什么?
What's the equivalent of cout for output to strings?
我应该已经知道了,但是... printf
sprintf
就像cout
____
一样?请举个例子。
听起来你正在寻找std::ostringstream
.
当然C++流不使用像 C 的 printf()
类型函数那样的格式说明符;它们使用 manipulators
。
示例,根据要求:
#include <sstream>
#include <iomanip>
#include <cassert>
std::string stringify(double x, size_t precision)
{
std::ostringstream o;
o << std::fixed << std::setprecision(precision) << x;
return o.str();
}
int main()
{
assert(stringify(42.0, 6) == "42.000000");
return 0;
}
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
ostringstream s;
s.precision(3);
s << "pi = " << fixed << 3.141592;
cout << s.str() << endl;
return 0;
}
输出:
pi = 3.142
下面是一个示例:
#include <sstream>
int main()
{
std::stringstream sout;
sout << "Hello " << 10 << "n";
const std::string s = sout.str();
std::cout << s;
return 0;
}
如果要清除流以供重复使用,可以执行
sout.str(std::string());
另请查看增强格式库。
std::ostringstream
您可以使用它来创建类似 Boost 词法强制转换的内容:
#include <sstream>
#include <string>
template <typename T>
std::string ToString( const T & t ) {
std::ostringstream os;
os << t;
return os.str();
}
使用中:
string is = ToString( 42 ); // is contains "42"
string fs = ToString( 1.23 ) ; // fs contains something approximating "1.23"
你对cout的概念有一点误解。 cout 是一个流,运算符<<是为任何流定义的。因此,您只需要另一个写入字符串的流即可输出数据。您可以使用标准流,如 std::ostringstream 或定义您自己的流。
所以你的类比不是很精确,因为cout不是像printf和sprintf那样的函数
相关文章:
- 什么相当于 Kotlin 上的C++指针?
- 霓虹灯中的_mm_hadd_ps相当于什么?
- 对于 poco 库来说,Boost_USE_STATIC_LIBS相当于什么?
- 什么 clang-format 相当于 rustfmt 的 indent_style=Block?
- C++ C 的双指针相当于什么?
- Visual Studio 编译器的 record-gcc-switch 相当于什么?
- 什么相当于英特尔实感 3D 摄像头 (SR300) 的 pmdGet3DCoordinates?
- 什么C++相当于winapi的MsgWaitForMultipleObjectsEx
- VB6 相当于 C++ 个字符数组是什么?
- C# 在<map>C++中相当于什么?
- opencv 相当于 matlab 的 fliplr() 是什么?
- C++中 Python 的列表[:x] 相当于什么?
- C++中的“字符串”相当于什么
- 什么相当于C++中的QVariant
- 相当于 Java 静态块的C++习语是什么?
- OSX相当于Linux g++-multilib是什么?
- C中的C++ '*&'相当于什么?它甚至存在吗?
- 德尔福中C++“const”返回类型相当于什么
- 在Tensorflow的C++ TensorShape API中,Python的None相当于什么?
- 输出到字符串的 cout 相当于什么?