The textbook, written in HTML, includes numerous C++ programming examples. However, C++ source code often contains three characters incompatible with HTML: <
, >
, and &
. However, HTML defines appropriate character entities to represent incompatible characters. Manually replacing the characters, even using the "find-and-replace" feature provided by most text editors, is tedious and error-prone. HTMLfix is a simple program that replaces the incompatible C++ characters with their corresponding character entities. It also surrounds the program with opening and closing HTML pre tags.
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string input; // (a) cout << "Input file: "; getline(cin, input); ifstream in(input); if (!in.good()) { cerr << "Unable to open " << input << endl; exit(1); } size_t ext = input.rfind('.'); // (b) string file = input.substr(0, ext); string output = file + ".html"; ofstream out(output); if (!out.good()) { cerr << "Unable to open " << output << endl; exit(1); } |
out << "<pre>"; // (c) char c; while (in.get(c)) // (d) switch(c) { case '<': // (e) out << "<"; break; case '>': out << ">"; break; case '&': out << "&"; break; default: // (f) out.put(c); break; } out << "</pre>" << endl; // (c) return 0; } |
View | Download | Comments |
---|---|---|
HTMLfix.cpp | HTMLfix.cpp | An example program reading and processing a file one character at a time. |