C++:字符串流有什么好处? [英] C++: what benefits do string streams offer?

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

问题描述

谁能告诉我一些在 C++ 中使用字符串流的实际例子,即使用流插入和流提取运算符输入和输出到字符串流?

could any one tell me about some practical examples on using string streams in c++, i.e. inputing and outputing to a string stream using stream insertion and stream extraction operators?

推荐答案

您可以使用字符串流将任何实现 operator << 的内容转换为字符串:

You can use string streams to convert anything that implements operator << to a string:

#include <sstream>

template<typename T>
std::string toString(const T& t)
{
  std::ostringstream stream;
  stream << t;

  return stream.str();
}

甚至

template <typename U, typename T>
U convert(const T& t)
{
  std::stringstream stream;
  stream << t;

  U u;
  stream >> u;

  return u;
}

这篇关于C++:字符串流有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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