C++中如何在std::cin这类iostream对象前插入字符串?
std::cin for an Unmodifiable print Function Got it, let's tackle this problem: you need to insert a string at the start of the std::cin input stream before passing it to the unmodifiable print function. The Boost.Iostreams library (which you already hinted at in your code comment) is perfect for this—it lets you chain multiple input sources together seamlessly.
Step-by-Step Solution
Here's how to modify your main function to make this work:
- Include necessary headers: You'll need
<boost/iostreams/filtering_stream.hpp>to create the combined stream, plus<sstream>to wrap your header string in a stream. - Wrap the header in a string stream: Convert your
headerstring into anstd::istringstreamso it can be treated as a standard input source. - Chain streams with
filtering_istream: Add the header stream first, thenstd::cin—this ensures theprintfunction reads the header content before any input from standard cin.
Complete Working Code
#include <iostream> #include <string> #include <sstream> #include <boost/iostreams/filtering_stream.hpp> void print(std::istream & in){// function not to be modified std::string str; in >> str; std::cout<< str << std::endl; in >> str; std::cout<< str << std::endl; } int main() { std::string header = "hello "; // Wrap the header string into an input stream std::istringstream header_stream(header); // Create a combined stream: first read header, then std::cin boost::iostreams::filtering_istream in; in.push(header_stream); in.push(std::cin); // Pass the combined stream to the unmodifiable print function print(in); }
How It Works
- The
filtering_istreamacts as a single input stream that reads sequentially from each source youpushinto it. It will first consume all content fromheader_stream(your "hello " string), then automatically switch to reading fromstd::cinonce the header stream is empty. - Since
filtering_istreamis compatible withstd::istream&, it works perfectly with the unmodifiableprintfunction—no changes needed there.
Compilation Note
When compiling this code, you'll need to link against the Boost Iostreams library. For example, with GCC:
g++ your_file.cpp -o your_program -lboost_iostreams
Alternative: No Boost?
If you can't use Boost, you'd need to create a custom std::streambuf that combines the header string and std::cin's buffer. This is more verbose, but the core idea is:
- Subclass
std::streambuf - Override the
underflow()method to first read characters from the header string, then delegate tostd::cin's buffer once the header is exhausted. - Attach this custom buffer to an
std::istreaminstance and pass it toprint.
That said, the Boost approach is far cleaner and less error-prone for this specific use case.
内容的提问来源于stack exchange,提问作者keen_learner

