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

The C-string solution for the Rolodex problem is logically identical to string class solution presented in the previous section, differing only in the kind of strings and getline function used. For brevity, the example omits the initial development.

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


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

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

	/*char	line[100];

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

	while (!in.eof())					// (a)
	{
		char	name[20];				// (b)
		in.getline(name, 20, ':');			// (c)

		char	address[35];				// (b)
		in.getline(address, 35, ':');			// (c)

		char	phone[20];				// (b)
		in.getline(phone, 20, '\n');			// (c)
		//in.getline(phone, 20);			// (d)

		cout << left << setw(20) << name <<
			setw(35) << address <<
			setw(20) << phone << endl;
	}

	return 0;
}
c-rolodex.cpp. The example opens a file in text mode, verifies that the file opened correctly, and reads the file's contents, parsing each line into separate fields. The program suffers the same faults as the string version: an extraneous loop if the file exists but is empty and fails to handle input that does not conform to the expected pattern.
  1. Loop while not at the end of the file. If the file exists but is empty, the program loops once without reading data.
  2. Define a C-string variable to hold the input field.
  3. Reads one field from the input stream in, stores the text in the C-string variable, and returns after reading and discarding the delimiter.
  4. Alternatively, the program can use the two-parameter version for the last getline call, which stops after reading and discarding the newline at the end of each line in the file.

Downloadable File

ViewDownloadComments
c-rolodex.cpp c-rolodex.cpp An example program reading and parsing fields from a line-oriented data file, saving them in C-strings for processing.