/*--- cheesy_count_lines example from LA-run Final Exam Review in 3:00 pm CS 111 - Week 15 Lab presented by: Enrique Lopez adapted by: Sharon Tuttle last modified: 2025-12-12 ---*/ #include <cstdlib> #include <iostream> #include <string> #include <cmath> #include <fstream> using namespace std; /*=== signature: cheesy_count_lines: string -> int purpose: expects the name of a file (reachable from the current working directory), has the side-effect of opening that file for reading, and returns the number of lines in that file. If the file cannot be opened, return a line count of -1. tests: for a file boynton.txt containing: Moo Baa La la la cheesy_count_lines("boynton.txt") == 3 for a file lookity.txt containing: 1 2 3 4 cheesy_count_lines("lookity.txt") == 4 for a non-existent file fictitious.txt: cheesy_count_lines("fictitious.txt") == -1 ===*/ int cheesy_count_lines(string filename) { ifstream read_fin; read_fin.open(filename); // if read of given filename failed, just return -1 if (read_fin.fail()) { return -1; } // if REACH here, filename WAS opened for reading int num_lines = 0; string next_line; // for each line successfully read, increment num_lines while (getline(read_fin, next_line)) { num_lines++; } read_fin.close(); return num_lines; } /*--- test the function above ---*/ int main() { cout << boolalpha; // create files for testing cheesy_count_lines ofstream tests_fout; tests_fout.open("boynton.txt"); tests_fout << "Moo" << endl << "Baa" << endl << "La la la" << endl; tests_fout.close(); tests_fout.open("lookity.txt"); tests_fout << 1 << endl << 2 << endl << 3 << endl << 4 << endl; tests_fout.close(); cout << endl; cout << "*** Testing: cheesy_count_lines ***" << endl; cout << (cheesy_count_lines("boynton.txt") == 3) << endl; cout << (cheesy_count_lines("lookity.txt") == 4) << endl; cout << (cheesy_count_lines("fictitious.txt") == -1) << endl; cout << endl; return EXIT_SUCCESS; }