title: Run .exe and redirect stdin and out
body: <p>For most of my life, I've been using <code>cstdio</code>. Now I'm trying to shift over to <code>iostream</code>.</p>
  
  <p>Suppose I have a separate program called "foo.cpp" that looks like this:</p>
  
  <pre><code>int main(){ // foo.cpp
      int x;
      std::cin &gt;&gt; x;
      std::cout &lt;&lt; x + 5 &lt;&lt; "\n";
  }
  </code></pre>
  
  <p>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 <code>freopen</code> like so:</p>
  
  <pre><code>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"
  }
  </code></pre>
  
  <p>Now I'm trying to redirect <code>std::cin</code> and <code>std::cout</code> to stringstreams. Something like this:</p>
  
  <pre><code>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"
  }
  </code></pre>
  
  <p>But what I've learned is that <code>std::cin</code> and <code>std::cout</code> was not redirected when executing "foo.exe". The program now expected user input and will print to <code>std::cout</code>. When execution of "foo.exe" was done, <code>std::cin</code> and <code>std::cout</code> within "bar.cpp" still remained redirected to <code>instr</code> and <code>outstr</code> respectively.</p>
  
  <p>My question is, is there a way to do it with <code>iostream</code> like I intended, or am I stuck with using <code>freopen</code>?</p>