如何使用C ++ std :: ostream与printf样格式化? [英] How to use C++ std::ostream with printf-like formatting?

查看:200
本文介绍了如何使用C ++ std :: ostream与printf样格式化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学习C ++。 cout std :: ostream 类的实例。
如何打印格式化的字符串?



我仍然可以使用 printf 学习更多C ++风格方法,可以采取所有C ++的好处。我认为这应该是可能的 std :: ostream 但是我找不到正确的方式。

解决方案

直接使用 std :: ostream 可以做的唯一事情是众所周知的<< -syntax:

  int i = 0; 
std :: cout<< 这是一个数字:<一世;

还有各种 IO操纵器 ,可用于影响整数,浮点数等的格式,位数等等。 p>

但是,这与 printf 的格式化字符串不同。 C ++ 11不包括任何允许以与使用 printf 相同的方式使用字符串格式化的工具(除了 printf <



对于提供 printf 的库,你可以在C ++中使用它。 code> -style功能,有 boost :: format ,可启用此类代码(从概要复制):

  std :: cout<< boost :: format(writing%1%,x =%2%:%3%-th try)%toto%40.23%50; 

另请注意,有一个包含 printf 未来版本的标准。如果这被接受,诸如下面的语法可以变得可用:

  std :: cout< std :: putf(this is a number:%d \\\
,i);


I am learning C++. cout is an instance of std::ostream class. How can I print formatted string with it?

I still can use printf, but I want to learn more C++ style method which can take all C++ benefits. I think this should be possible with std::ostream but I can't find proper way.

解决方案

The only thing you can do with std::ostream directly is the well known <<-syntax:

int i = 0;
std::cout << "this is a number: " << i;

And there are various IO manipulators that can be used to influence the formatting, number of digits, etc. of integers, floating point numbers etc.

However, that is not the same as the formatted strings of printf. C++11 does not include any facility that allows you to use string formatting in the same way as it is used with printf (except printf itself, which you can of course use in C++ if you want).

In terms of libraries that provide printf-style functionality, there is boost::format, which enables code such as this (copied from the synopsis):

std::cout << boost::format("writing %1%,  x=%2% : %3%-th try") % "toto" % 40.23 % 50;

Also note that there is a proposal for inclusion of printf-style formatting in a future version of the Standard. If this gets accepted, syntax such as the below may become available:

std::cout << std::putf("this is a number: %d\n",i);

这篇关于如何使用C ++ std :: ostream与printf样格式化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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