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; }
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.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