2

I am to use filtering_istream as a wrapper around std::cin. but it is not working as I expected. It is waiting for the E.O.F please help me to understand the behaviour.

#include <iostream>
#include <boost/iostreams/filtering_stream.hpp>
// compile using g++ -std=c++11 -lboost_iostreams

int main(){
    boost::iostreams::filtering_istream cinn(std::cin);
    std::cout << "Write something:";

    char c;
    while(true){
        cinn.get(c);
        std::cout << "Your character is : " << c << "\n";
        if(c=='.') break;
    }
}

I want it to work similar to this code.

#include <iostream>
#include <boost/iostreams/filtering_stream.hpp>

int main(){
    //boost::iostreams::filtering_istream cinn(std::cin);
    std::cout << "Write something:";

    char c;
    while(true){
        std::cin.get(c);
        std::cout << "Your character is : " << c << "\n";
        if(c=='.') break;
    }
}

Output of the code1 is

$./a.out
hello
how.are_you
Write something:Your character is : h
Your character is : e
Your character is : l
Your character is : l
Your character is : o
Your character is : 

Your character is : h
Your character is : o
Your character is : w
Your character is : .

output of code2 is

$./a.out
Write something:hello
Your character is : h
Your character is : e
Your character is : l
Your character is : l
Your character is : o
Your character is : 

how.are_you
Your character is : h
Your character is : o
Your character is : w
Your character is : .

Code 2 gives output as I expect. It read each line and process it. while Code1 reads all the lines till it get E.O.F. and then it prints output.

Both the codes behave differently. I am unable to understand this behavior. Please help. Thanks in Advance.

srbcheema1
  • 544
  • 4
  • 16

1 Answers1

0

You're looking at buffering. Buffering occurs at many levels. In this case you're likely looking at the buffering inside the filtering stream.

You can play around with things like

  • set_device_buffer_size
  • set_filter_buffer_size
  • set_pback_buffer_size

On my machine, I got the results you want using (docs)

boost::iostreams::filtering_istream cinn(std::cin, 0, 1);
sehe
  • 374,641
  • 47
  • 450
  • 633