我将使用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;
    }
}

代码1的输出是
$./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。然后打印输出。

两种代码的行为均不同。我无法理解这种行为。请帮忙。提前致谢。

最佳答案

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

您可以玩这样的事情

  • set_device_buffer_size
  • set_filter_buffer_size
  • set_pback_buffer_size

  • 在我的机器上,我得到了想要使用的结果(docs)
    boost::iostreams::filtering_istream cinn(std::cin, 0, 1);
    

    09-26 06:06