Prev Next

Input and Output

Output using the iostream library (C++)

You can perform output to a monitor or a file using either the iostream or stdio libraries in C++. In C, you can only use the stdio library.

#include <iostream>
using namespace std;

Variable cout refers to the standard output (usually the monitor). Binary operator << is used to write. You can write many different kinds of things, such as integers, characters and strings, and you can perform several writes in one statement. For example,

  int n = 2;
  char c = 'a';
  cout << n << c;
writes 2 and a, with no space between them. You can include null-terminated strings as well, as in
  cout << "Thank you for running me" << endl;
where endl is just "\n". Some other operations using cout are as follows.

OperationMeaning
cout.write(buf,n); Write n characters from character array buf.
cout.flush(); When you print on cout, what you print goes into a buffer until the buffer becomes full. Then the contents of the buffer is actually printed. This delayed printing can be a problem sometimes. Function flush prints what is in the buffer.
cout.close(); Write an end-of-file marker to the file being written by cout. This terminates the file. After doing this, you can no longer write to cout.

Variable cout is just one variable of type ofstream, used to print to a file.

Writing to a file

You can create other ofstream variables, and tie them to files. To do this, include header file fstream. For example,

 
ofstream myout("myfile", ios::trunc | ios::out);
declares variable myout of type ofstream. It also uses a constructor that ties this variable to the system file called "myfile". The file will be emptied, if it already exists (option ios::trunc). If, instead of ios::trunc, you write ios::append, new information will be added to the end of an existing file. Anything that you write will be written into that file. When you are done writing to the file, close it, using the close function.

Output using the stdio library (C or C++)

Many experience C+++ programmers prefer the stdio library to the iostream library. To use this in a C++ program, include header file cstdio.

#include <cstdio>
using namespace std;
To write in C style, you can use library functions printf and fprintf. The first parameter to printf is a format, a string that tells what the output should look like. Within the format are sequences that start with %, and that indicate that the value of the next parameter should be put here. For example
  int m = 3;
  int n = 5;
  printf("I have n = %i and m = %i\n", n, m);
prints
I have n = 5 and m = 3
Here are some of the formats that are available.

FormatUse
%c Print a character.
%i Print an integer. %3i prints the integer in three spaces, padded on the left with blanks. If the integer is too large for three spaces, more will be used. %-3i is similar, but pads on the right with blanks.
%li Print a long integer. %5li prints the long integer in five spaces.
%f Print a floating point number. %6.2f prints it in six spaces, with two digits to the right of the decimal point.
%s Print a string. The corresponding parameter must point to a null-terminated string. %12s prints the string in 12 characters, padded on the left with blanks.
%% Print a % character.

Writing to a file

To print on a file, you must open the file. Use the following.

FILE* f = fopen(filename, "w");
to open a file for writing. Now use
fprintf(f, format, ...);
to print on the file. For example,
fprintf(f, "I have %i peaches\n", num_peaches);
Finally, to close the file, use
fclose(f);
For example, here is a function that writes file "test.out", putting string
abcdefghijklmnopqrstuvwyz
in the file.

void print_alphabet()
{
  char c;
  FILE* outf = fopen("test.out", "w");

  for(c = 'a'; c <= 'z'; c++) {
    fprintf(outf, "%c", c);
  }
  fprintf(outf, "\n");
  fclose(outf);
}

Input using the iostream library (C++)

You can perform input from a keyboard or a file in either the C or C++ styles. (C style can be used in either C or C++ programs. C++ style can only be used in C++ programs.) Use the same header files as for output.

Variable cin refers to the standard input (usually the keyboard). Binary operator >> is used to read. You can read many different kinds of things, such as integers, characters and strings, and you can perform several reads in one statement. For example,

  int n;
  char c;
  cin >> n >> c;
reads an integer, and puts it into variable n, and then reads a character, and puts it into variable c. If you read a string (type char*) using >>, characters will be read up to a space or newline, and put into the string. Be sure that there is enough room in the arrray. If you read a character, you will get one character, except that white-space characters (blank, tab, newline) are skipped.

Some other operations using cin are as follows.

OperationMeaning
cin.eof() True if cin is at the end of file.
cin.fail() True if the most recent operation done on cin failed. This can also be used to test whether opening a file failed.
cin.get() Returns the next character, or the special value EOF (-1) if there is no more data in the file. The type of cin.get() is int, not char. This function does not skip over white-space characters.
cin.peek() Returns the next character, without removing it from the stream. Like cin.get(), it returns an int, and returns EOF on end-of-file.
cin.putback(c); Puts character c back at the front of the stream.
cin.read(buf,n); Reads n characters and puts them into buffer buf. buf must be a pointer to an array of characters that you have already allocated.
cin.getline(buf,n); Reads a line and puts it into buf. It replaces the end of line character by a null character. n is the size of buf. No more than that many characters will be read.
cin.close(); Closes stream cin. ( You cannot read from cin after closing it.)

Reading a file

You can read from a file. To do so, include header file fstream.

To read from a file, just create a stream attached to that file. Declaration
 ifstream f(name, ios::in);
creates variable f, a stream bound to file name. You can use the same operations on f as on cin. For example,
  ifstream ins("test.txt");
  int k;
  ins >> k;
  ins.close();
creates a stream called ins and reads an integer from it. When you are done with a stream, close it, as is done above. But don't close it until you are done reading from it. The example only wants to read one integer, and no more.

Input using the stdio library (C or C++)

To read in C style, you can use library functions scanf and fscanf. Include header file cstdio to use these. The first parameter to scanf is a format, telling what kind of data to read. Usually, the format just has indications of types that are similar to the indications in output formats. For example, to read two integers m and n, you would write

  scanf("%i%i", &m, &n);
Notice the need to use &. The parameters after the format are call-by-pointer. If you use format %s, then a string will be read up to a space or newline.

Reading a file

To read from a file, you must open the file for reading, and use fscanf. For example,

  int n;
  FILE* inf = fopen("infile.txt", "r");
  fscanf(inf, "%i", &n);
  fclose(inf);
reads a single integer from file infile.txt. A handy function is fgets. fgets(s,n,f) reads a line from file f, and puts it into array of characters s. Array s must have physical size at least n. The newline character is put at the end of , and s is null-terminated. At most n-1 characters are read, leaving a spot for the null character.


Prev Next