输出到字符串的 cout 相当于什么?

What's the equivalent of cout for output to strings?

本文关键字:相当于 什么 cout 字符串 输出      更新时间:2023-10-16

我应该已经知道了,但是... 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那样的函数