6

我应该已经知道了,但是……是printf这样sprintf吗?请举个例子。cout____

4

5 回答 5

13

听起来您正在寻找std::ostringstream.

当然,C++ 流不使用格式说明符,如 C 的printf()-type 函数;他们使用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;
}
于 2011-05-06T23:55:17.667 回答
1
 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"
于 2011-05-06T23:49:06.640 回答
1
#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
于 2011-05-07T00:00:04.230 回答
1

这是一个例子:

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

另请查看Boost Format库。

于 2011-05-07T00:08:37.707 回答
-1

你对 cout 的概念有一点误解。cout 是一个流,运算符 << 是为任何流定义的。因此,您只需要另一个写入字符串的流即可输出您的数据。您可以使用标准流,如 std::ostringstream 或定义您自己的流。

所以你的类比不是很精确,因为 cout 不是像 printf 和 sprintf 这样的函数

于 2011-05-06T23:51:27.007 回答