Streams

cin, cout, and cerr are predefined streams in C++. make sure you have included <iostream> and have used "using namespace std;" at the start of the program.

To open a file for reading, use code like the following:

ifstream inFile("name", ios::in);

To open a file for output use code like:

ofstream outfile("name", ios::out);

Make sure you have included <fstream> before using these functions.

To input a character from an input stream, use the get() function:

char ch
inFile.get(ch);

To output a character, use the put() function:

outFile.put(ch);

Here is a sample program that gets characters from standard input and puts them into the file copy.out
#include <fstream>

int main()
{
   //open a file copy.out for output
   ofstream outFile("copy.out");

   if (! outFile)
   {
      cerr << "cannot open "copy.out" for output\n";
      return -1;
   }

   char ch;
   while (cin.get(ch))
      outFile.put(ch);
}
To open a file for input only, an ifstream class object is used.
#include <fstream>

int main()
{
   cout << "filename: ";
   string file_name;
   cin >> file_name;

   //open a file copy.out for input
   ifstream inFile(file_name.c_str() );

   if (! inFile)
   {
      cerr << "unable to open input file: "
	   << file_name << " --bailing out! \n";
      return -1;
   }

   char ch;
   while (inFile.get(ch))
      cout.put(ch);
}

Command Line Arguments

If you want to obtain parameters from the command line you need to define your main function as follows:

int main(int argc, char *argv[])

When you type the programs name followed by some parameters, the shell passes all the words on the command line to the program as an array of NUL-terminated character strings. These can be accessed in your program using argc, which is the total count of the parameters including the program name, and argv[] which is the 0 based index array of strings.

For example, to access the program executable name use argv[0]. To reference the first parameter use argv[1]. If there were only two parameters, (the program name and the first parameter), then argc would equal 2.


The following program prints out the command line, including the name of the program.
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
	int i;

	for (i = 0; i < argc; i++)
	{
		cout << argv[i] << " ";
	}
	cout << endl;
	return 0;
}