Boost :: iostreams :: filtering_istreams等待E.O.F.

时间:2018-03-19 15:03:17

标签: c++ boost iostream boost-iostreams

我将使用filtering_istream作为std :: cin的包装器。 但它没有像我预期的那样工作。 它正在等待E.O.F. 请帮助我理解这种行为。

#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;
    }
}

我希望它与此代码类似。

#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;
    }
}

code1的输出是

$./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 : .

code2的输出是

$./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 : .

代码2提供了我期望的输出。它读取每一行并处理它。而Code1读取所有行,直到获得E.O.F.然后打印输出。

两种代码的行为都不同。我无法理解这种行为。请帮忙。在此先感谢。

1 个答案:

答案 0 :(得分:0)

你正在寻找缓冲。缓冲发生在许多级别。在这种情况下,您可能正在查看过滤流中的缓冲。

你可以玩

之类的东西
  • set_device_buffer_size
  • set_filter_buffer_size
  • set_pback_buffer_size

在我的机器上,我得到了你想要的结果(docs

boost::iostreams::filtering_istream cinn(std::cin, 0, 1);