Stream from a String Instead of CIN in C++

Posted by in Software

TL;DR: You can stream from a string instead of STDIN. Code is simple and is listed below.

A project I did recently had a requirement to overload the >> operator use and STDIN to load data. The problem was not the overload itself, but the fact that testing would introduce a manual side. To get around that, I needed a way to stream data from a string instead of STDIN.

The solution is presented below:

To use it, all you need to do is:

  1. Create a string:

    It is notable the stream will be read in the same fashion as STDIN, with "\n" as delimiter :)

  2. Create your stream:

  3. Load the stream:

    count can be strlen(str) but can also be a smaller value (in this case, it only means not all values will be loaded in your object).

A little experiment: If you find this post and ad below useful, please check the ad out :-)