The first Rolodex problem solution is based on the C++ string class. It's generally easier to write and test programs incrementally rather than wait until we finish to test them. Developing software with frequent write-test cycles makes it easier to localize new problems: they are likely in the most recently added code, meaning there are fewer places for bugs to hide, narrowing our search for them. Once we verify a logical group of statements, we can more confidently rely on them.
#include <iostream> #include <fstream> #include <iomanip> #include <string> using namespace std; int main() { ifstream in("rolodex.txt"); if (!in.good()) { cerr << "Unable to open \"rolodex.txt\"\n"; exit(1); } return 0; }
The validation test, based on the good function, is simple and generally effective. However, it fails to detect an easily overlooked condition because, technically, it isn't an error. If a file exists but is empty, the open operation doesn't set any error flags or the eofbit, but it does set the goodbit to 1.
Programs often subject file input to complex operations, and if a program exhibits a problem, it's easy to suspect those operations. From personal experience, I know how frustrating it is to focus on the processing operations only to discover that the failure results from the comparatively simple file-read operation. Therefore, I recommend validating the file-read code before processing the file's contents.
#include <iostream> #include <fstream> #include <iomanip> #include <string> using namespace std; int main() { ifstream in("rolodex.txt"); if (!in.good()) { cerr << "Unable to open \"rolodex.txt\"\n"; exit(1); } string line; while (getline(in, line)) cout << line << endl; return 0; }
At this time, create the rolodex.txt file and compile and run the program. If the program's output is identical to the input file's contents, continue to the final step; otherwise, look for a logical error in the read loop before proceeding. The highlighted code is NOT part of the final program and must be removed or commented out of the final program.
#include <iostream> #include <fstream> #include <iomanip> #include <string> using namespace std; int main() { ifstream in("rolodex.txt"); if (!in.good()) { cerr << "Unable to open \"rolodex.txt\"\n"; exit(1); } /*string line; while (getline(in, line)) cout << line << endl;*/ while (!in.eof()) { string name; // (a) getline(in, name, ':'); // (b) string address; // (a) getline(in, address, ':'); // (b) string phone; // (a) getline(in, phone, '\n'); // (b) //getline(in, phone); // (c) cout << left << setw(20) << name << setw(35) << address << setw(20) << phone << endl; } return 0; }
View | Download | Comments |
---|---|---|
s-rolodex.cpp | s-rolodex.cpp | An example program reading and parsing fields from a line-oriented data file, saving them in strings for processing. |