For most of my life, I've been using cstdio
. Now I'm trying to shift over 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. In the past, if I wanted to redirect stdin and stdout to a file, I would use freopen
like so:
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'm trying to redirect std::cin
and std::cout
to stringstreams. Something like this:
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 what I've learned is that std::cin
and std::cout
was not redirected when executing "foo.exe". The program now expected user input and will print to std::cout
. When execution of "foo.exe" was done, std::cin
and std::cout
within "bar.cpp" still remained redirected to instr
and outstr
respectively.
My question is, is there a way to do it with iostream
like I intended, or am I stuck with using freopen
?