简体   繁体   中英

Create istream and ostream objects in C++

I read that cout and cin are objects of classes std::istream and std::ostream. Can there be user defined objects like cout and 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.

To handle strings I'd recommend using std::stringstream .
The std::stringstream class is derived from 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::{i,o}fstream - data comes from / goes to a file

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.

You just have to be precise and knowledgeable about what you actually want them to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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