简体   繁体   English

在C ++中创建istream和ostream对象

[英]Create istream and ostream objects in C++

I read that cout and cin are objects of classes std::istream and std::ostream. 我读到cout和cin是std :: istream和std :: ostream类的对象。 Can there be user defined objects like cout and cin ? 用户定义的对象可以有cout和cin吗?

eg. 例如。 How can I do something like this : 我该如何做这样的事情:

     ostream obj;
     obj<<"string"<<endl;

EDIT 1 : I want to define an object that can replicate cout and cin without messing with their in-built definitions. 编辑1:我想定义一个对象,该对象可以复制cout和cin而不会弄乱它们的内置定义。

To handle strings I'd recommend using std::stringstream . 为了处理字符串,我建议使用std :: stringstream
The std::stringstream class is derived from istream. std :: stringstream类是从istream派生的。

std::stringstream obj;

obj << "Hello World" << endl;
// You can convert it to a string afterwards
 std::string myString = obj.str();

Yes, you can create any stream you want. 是的,您可以创建所需的任何流。

Since a stream is a flow of data with a source and a sink, you typically want to use either of the following: 由于流是具有源和接收器的数据流,因此通常需要使用以下任一方法:

  • std::stringstream - add data yourself, access it in stream form std::stringstream自己添加数据,以流形式访问
  • std::{i,o}fstream - data comes from / goes to a file std::{i,o}fstream数据来自/进入文件

std::cout and std::cin are particular instances of streams that happen to be connected to STDOUT and STDIN respectively, but there's no reason you can't make your own streams. std::coutstd::cin是流的特定实例,这些流恰巧分别连接到STDOUT和STDIN,但是没有理由您不能创建自己的流。

You just have to be precise and knowledgeable about what you actually want them to do. 您只需要对他们实际想要他们做什么的事情有足够的了解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM