1

I have created a basic console application. I would like to know how I could take the output and write it into a text file.

John Dibling
  • 99,718
  • 31
  • 186
  • 324
CNoob9799
  • 17
  • 1
  • 3

1 Answers1

5

There are several ways to do this.

(1) You can use the command line to redirect the output of your program to a file. You would do this in Windows from the shell as

madlib-program.exe > outputFile

and in Mac/Linux from the command line as

./madlib-program > outputFile

(2) You could replace all of your program's output calls with file writing operations. For example, if you were using streaming IO, you could start the program by opening an output file:

ofstream out("output-file.txt");

and then replace all usage of cout with out:

cout << "Hello, world" << endl;

becomes

out << "Hello, world!" << endl;

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • thanks a lot this really helped, but is there a possible way that i could then have the file save to my documents – CNoob9799 Jun 22 '12 at 02:39
  • @CNoob9799, Pass a full path instead of a relative one. – chris Jun 22 '12 at 02:40
  • @CNoob9799- Sure! You can specify any output file you'd like using either of the above approaches. You would probably have the output file be something like `C:\Users\[you]\Documents`. If you use the `ofstream` approach, remember to write this as `C:\\Users\\[you]\\Documents`, since `\` is normally the start of an escape sequence. – templatetypedef Jun 22 '12 at 02:41
  • @CNoob9799, Also, in Vista and up, I think it's represented by `%USERPROFILE%\Documents` as well. – chris Jun 22 '12 at 02:43
  • sorry to bother you again i used the ofstream method i don't know where to put the C:\\Users\\[me]//documents in the code – CNoob9799 Jun 22 '12 at 02:51
  • @CNoob9799- When you open the file, you need to specify the file path. The suggestion I offered in the answer was to open up `output-file.txt`. Just change that piece. That said, you should probably read up on the streams library for future reference. – templatetypedef Jun 22 '12 at 02:52