The first part of the example uses functions and operators from the string class. Please review the following as needed:
The textbook, which is written in HTML, includes many C++ programming examples. However, source code written in C++ and other languages often contain three characters that are not compatible with HTML: <
, >
, and &
. For these characters to display correctly in a web browser, I need to replace them with the appropriate HTML encodings. Manually replacing each character is a tedious and error-prone task. I need a simple program that can find and replace all of the characters at once and save the modified code in a new file. And, while we're at it, it would be nice to have the program add some simple boiler-plate formatting as well. The following C++ program, HTMLfix, performs these tasks for C++, Java, C#, and similar programming languages.
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string input; // (a) cout << "Input file: "; getline(cin, input); ifstream in(input); // (b) if (!in.good()) // (c) { cerr << "Unable to open " << input << endl; exit(1); } size_t ext = input.rfind('.'); // (d) string file = input.substr(0, ext); //cout << file << endl; string output = file + ".html"; // (e) ofstream out(output); // (f) if (!out.good()) // (g) { cerr << "Unable to open " << output << endl; exit(1); } out << "<h1>" << input << "</h1>" << // (h) endl << endl << "<pre>"; while (!in.eof()) // (i) { char c; // (j) in.get(c); // (k) switch(c) // (l) { case '<': out << "<"; break; case '>': out << ">"; break; case '&': out << "&"; break; default: // (m) out.put(c); //out << c; break; } } out << "</pre>" << endl; // (n) return 0; } |
|
* The function call stores data in the parameter c - that is, it returns data through the parameter, which requires and INOUT passing technique, eliminating pass by value. The variable c is not an array and the function call does not include the address of operator, &, which eliminates pass by pointer. So, the get function must use pass by reference.