For most of my life I used cstdio . Now I'm trying to switch to iostream .
Suppose I have a separate program called "foo.cpp" that looks like this:
int main(){ // foo.cpp int x; std::cin >> x; std::cout << x + 5 << "\n"; }
In another program called "bar.cpp", I call the foo executable. Previously, if I wanted to redirect stdin and stdout to a file, I would use freopen as follows:
int main(){ // bar.cpp, redirecting stdin and stdout freopen("foo.in", "r", stdin); // Suppose "foo.in" contains a single integer "42" freopen("foo.out", "w", stdout); system("foo.exe"); // "foo.out" will contain "47" }
Now I am trying to redirect std::cin and std::cout to stringstreams. Something like that:
int main(){ // bar.cpp, redirecting cin and cout std::istringstream instr("62"); std::ostringstream outstr; std::cin.rdbuf(instr.rdbuf()); std::cout.rdbuf(outstr.rdbuf()); system("foo.exe"); // outstr should contain "67" }
But I realized that std::cin and std::cout were not redirected while running "foo.exe". The program now expects user input and will print before std::cout . When the execution of "foo.exe" was executed, std::cin and std::cout inside "bar.cpp" still remained redirected to instr and outstr respectively.
My question is: is there a way to do this with iostream , as I expected, or am I sticking to using freopen ?
source share