// ---------------------------------------------------------------------------- // CntChrsDAT.cpp // Written by: The Professor // Last Modified: Fall 2020 // Description: // Program to Read a text file // and Keep track of the number of occurrences of each character // ASCII codes 0 to 127 // ---------------------------------------------------------------------------- #include #include #include #include // for use of std::stringstream using namespace std; int main() { // Could use argv and argc to allow user specified input file // But for simplicitly it is hardcoded string filename = "ICA320_input.txt"; ifstream inputFile(filename.c_str()); // The below is probably a bad idea if the file is REALLY big // but will work for this exercise stringstream buffer; buffer << inputFile.rdbuf(); string contents(buffer.str()); // Now set up to count characters // This is effectively a Direct Address Table // The key into the table is the Decimal // number associated with the character per ASCII encoding int charCount[128]; // Initialize the counts to zero for (int i=0; i < 128; i++) { charCount[i] = 0; } // Loop through the contents and count them for (unsigned int i=0; i < contents.size(); i++) { char ch = contents[i]; int key = ch; // force typecast to int charCount[key]++; } // Output the counts // First 32 characters are not printable for (int i=0; i < 32; i += 2) { cout << "character[ " << i << " ] -> " << charCount[i] << "\t"; cout << "character[ " << i+1 << " ] -> " << charCount[i+1] << endl; } for (int i=32; i < 126; i += 2) { char ch = i; // force i to be a character cout << ch << " -> " << charCount[i] << "\t\t\t\t"; ch = i+1; // force i to be a character cout << ch << " -> " << charCount[i+1] << endl; } // character 127 is delete char ch = 126; cout << ch << " -> " << charCount[126] << "\t\t"; cout << " character[ 127 ] -> " << charCount[127] << endl; inputFile.close(); return 0; }