1: //count_characters.cpp 2: //Reads a file of text and reports the number of upper case (capital) 3: //letters and the number of lower case (small) letters on each line of 4: //the file. The file may contain blank lines, and may also be empty, 5: //but in the latter case the program says nothing. 7: #include <iostream> 8: #include <fstream> 9: #include <cctype> //for access to the "isupper" and "islower" functions 10: using namespace std; 12: int main() 13: { 14: cout << "\nThis program counts the number of capitals and small " 15: "letters on each line of\na textfile. If no output is shown " 16: "below, make sure the input file is available\nand is non-empty, " 17: "since no message reporting either its absence or the fact\n" 18: "that it is empty is displayed.\n\n"; 20: const char NEW_LINE = '\n'; 22: ifstream inFile; 23: int lineCount = 0; 24: int upperCount; 25: int lowerCount; 26: char ch; 28: inFile.open("in_data"); //Assume file is present; no error 29: //message is displayed if it isn't 30: while (inFile) //Loop terminates when end-of-file reached 31: { 32: inFile.get(ch); //Read a character (unless there are none) 33: if (inFile) //Process character (if one actually read) 34: { 35: ++lineCount; 36: upperCount = 0; 37: lowerCount = 0; 38: while (ch != NEW_LINE) //Loop terminates at end-of-line 39: { 40: //How could the if...else-statement below be rewritten to 41: //improve "efficiency", assuming more lowercase letters 42: //than uppercase letters in the input data? 43: if (isupper(ch)) 44: ++upperCount; 45: else if (islower(ch)) 46: ++lowerCount; 47: inFile.get(ch); 48: } 49: cout << "Line " << lineCount << " contains " 50: << upperCount << " capitals and " 51: << lowerCount << " small letters.\n"; 52: } 53: } 54: cout << endl; 55: }