对于输出到字符串,cout是什么等价的? [英] What's the equivalent of cout for output to strings?

查看:184
本文介绍了对于输出到字符串,cout是什么等价的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该知道这个已经,但... printf sprintf as cout ____ 吗?请举个例子。

解决方案

听起来你正在寻找 std :: ostringstream

当然C ++流不使用格式说明符,如C的 printf() -type函数;他们使用 操纵器



根据要求提供示例:

  #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;
}


I should know this already but... printf is to sprintf as cout is to ____? Please give an example.

解决方案

It sounds like you are looking for std::ostringstream.

Of course C++ streams don't use format-specifiers like C's printf()-type functions; they use manipulators.

Example, as requested:

#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;
}

这篇关于对于输出到字符串,cout是什么等价的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆