#include #include #include #include #include void pause (void) { cout << "Hit any key to continue...\n"; getch (); } char get_replacement_character (char ch) { if ((ch >= 'a') && (ch <= 'z')) { return (char) ('A' + ('z' - ch)); } if ((ch >= 'A') && (ch <= 'Z')) { return (char) ('a' + ('Z' - ch)); } if ((ch >= '0') && (ch <= '9')) { return (char) ('0' + (((ch - '0') + 5) % 10)); } return ch; } void do_processing (ifstream &fin, ofstream &fout) { char next_char; int line_count = 0, blank_line_count = 0; bool current_line_all_blank = true, last_char_was_a_newline = true; fin >> resetiosflags (ios::skipws); for (;;) { fin >> next_char; if (fin.fail()) { // the read has failed for some reason if (fin.eof()) { // the read failed because we're at the end of the file. // there is nothing more to process - exit the processing loop break; } // the read failed for some other reason. when reading characters, this // is most unlikely, but it is possible. it could be, for example, that // the file being read has been corrupted (physically cannot be read). cout << "A file read error has occurred - processing aborted.\n"; return; } if (next_char == '\n') { // we're at the end of the current line line_count++; if (current_line_all_blank) { blank_line_count++; } current_line_all_blank = true; // reset for fresh line last_char_was_a_newline = true; } else { if (!isspace(next_char)) { current_line_all_blank = false; // we've seen something } last_char_was_a_newline = false; } fout << get_replacement_character (next_char); } // given an ideal input file, we should always see a newline character just // before we reach the end of the file. if this isn't the case, it means // that the last line of the file did not have a newline character. if (!last_char_was_a_newline) { cout << "\nWarning - the last input line is missing a newline char.\n"; // do usual end of line processing line_count++; if (current_line_all_blank) { blank_line_count++; } fout << '\n'; // add missing newline to the output file } cout << "\nEncoding complete - the input file contained " << line_count << " lines.\n" << "Of these, " << blank_line_count << " were completely blank.\n"; } void main (void) { char in_file_name[60], out_file_name[60]; ifstream fin; ofstream fout; for (;;) { cout << "Enter name of input file: "; cin >> in_file_name; fin.open (in_file_name); if (!fin.fail()) { break; } cout << "Unable to open input file - please try again.\n"; } cout << "Enter name of output file: "; cin >> out_file_name; fout.open (out_file_name); do_processing (fin, fout); pause (); }