title: Redirect cout to file c++
body: <p>I have a problem with my code. It has been a small school project, that I wish to enhance by redirecting the strings from a console window, into a ".txt" file. My problem is that I only get the last string printet. So my guess is I keep overwriting the CoolNumber.txt file, but I cannot see where to make the change, so i don't overwrite, but just add to the file.</p>
  
  <p>My code looks like the following:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string.h&gt;
  #include &lt;sstream&gt;
  #include &lt;fstream&gt;
  
  using namespace std;
  
  string intToChar[10] = { 
      "0",
      "1",
      "2abc",
      "3def",
      "4ghi",
      "5jkl",
      "6mno",
      "7pqrs",
      "8tuv",
      "9wxyz"
      };
  
  void CoolNumber(string number, string character)
  {
      ofstream file;
      file.open("CoolNumber.txt");
      streambuf* sbuf = cout.rdbuf();
      cout.rdbuf(file.rdbuf());
  
      if (number == "")
      {
          cout &lt;&lt; character &lt;&lt; ", " &lt;&lt; endl;
      }
      else
      {
          int length = intToChar[number[0]-'0'].size();
          for (int i = 0; i &lt; length; i++)
          {
              stringstream ss; 
              char c = intToChar[number[0]-'0'][i];
              string s;
              ss &lt;&lt; c;
              ss &gt;&gt; s; 
              CoolNumber(number.substr(1, number.size()), character + s);
          }
      }
  }
  
  int main()
  {
      string number = "27529250";
  
      cout &lt;&lt; "Type your mobilenumber: ";
      cin &gt;&gt; number;
      //int length = intToChar[5].length();
      //cout &lt;&lt; length &lt;&lt; endl;
      CoolNumber(number, "");
  }
  </code></pre>
  
  <p>I know my code works by cout to a console window, if it is written without this code</p>
  
  <pre><code>    ofstream file;
      file.open("CoolNumber.txt");
      streambuf* sbuf = cout.rdbuf();
      cout.rdbuf(file.rdbuf());
  </code></pre>
  
  <p>It would be awesome to get this code to work.</p>
  
  <p>P.s. I have tried looking at other topics here on StackOverflow, but can't seem to find any that works any better for me.</p>