14.8.3. c-rolodex.cpp: C-String I/O Example

The second solution for the Rolodex problem is similar to the previous one but is based on C-strings in place of the string class. For brevity, the example omits much of the common commentary from the previous demonstration. Please see the comments and the program development for the string-class solution.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
using namespace std;


int main()
{
	ifstream in("rolodex.txt");				// (a)

	if (!in.good())						// (b)
	{
		cerr << "Unable to open \"rolodex.txt\"\n";
		exit(1);
	}

	/*char	line[100];					// (c)

	while (in.getline(line, 100))
		cout << line << endl;*/

	while (!in.eof())					// (d)
	{
		char	name[20];				// (e)
		in.getline(name, 20, ':');			// (f) - 3-parameters
		cout << left << setw(20) << name;		// (g) & (i)

		char	address[35];				// (e)
		in.getline(address, 35, ':');			// (f) - 3-parameters
		cout << setw(35) << address;			// (g)

		char	phone[20];				// (e)
		in.getline(phone, 20);				// (h) - 2-parameters
		cout << setw(20) << phone << endl;		// (g)
	}

	return 0;
}
c-rolodex.cpp.
  1. Opens the file for reading in text mode
  2. Detects errors opening the file
  3. Test code that verifies the ability of the program to read the file
  4. Loop while not at the end of the file
  5. Define a C-string variable to hold part of the input
  6. Reads text from the input stream in, stores the text in the string variable, and stops reading when the delimiter (the third argument, the colon character in this example) is encountered. Discards the colon.
  7. Prints formatted output on the console
  8. Notice that the program uses the two-argument version of getline to read the last field. Reads text from the input stream in, stores the text in the string variable, and stops reading when the new line is encountered. Discards the new line.
  9. The left manipulator causes the output be be left justified in the space allocated by the setw manipulator; notice the order of the two manipulators - it is important

Downloadable File

c-rolodex.cpp