Question: When I run this code (C++): #include #include #include using namespace std; int main() { ifstream inClientFile; string fileName; // Open the file cout <
When I run this code (C++):
#include
using namespace std;
int main() { ifstream inClientFile; string fileName; // Open the file cout << "Enter the name of a file to read from:" << endl; cin >> fileName; inClientFile.open(fileName.c_str());
// Check if file can be opened if (!inClientFile) { cerr << endl; cerr << "File cannot be opened" << " " << fileName << endl; exit (1); }
// Initialize variables to keep track of number of commented lines, // maximum length of commented line and non-commented line int totalLines = 0; int commentLines = 0; int maxCommentLength = 0; int maxCodeLength = 0; string maxCommentLine = ""; string maxCodeLine = ""; string line;
while(getline(inClientFile, line)) { totalLines++;
if(line.length() > 0) { if((line[0] == '#' && line[1] == '#') || (line[0] == '/' && line[1] == '/')) { commentLines++; if(line.length() > maxCommentLength) { maxCommentLength = line.length(); maxCommentLine = line; } } else { if(line.length() > maxCodeLength) { maxCodeLength = line.length(); maxCodeLine = line; } } } }
// Close the file inClientFile.close();
// Print results cout << "Total Number of Lines: " << totalLines << endl; cout << "Number of commented lines: " << commentLines << endl; cout << "Maximum Length of commented lines: " << maxCommentLength << endl; cout << "Maximum Length of non-commented lines: " << maxCodeLength << endl; cout << "Commented line of maximum length: " << "\"" << maxCommentLine << "\"" << endl; cout << "Non-commented line of maximum length: " << "\"" << maxCodeLine << "\"" << endl; return 0; }
I get an output of:
Enter the name of a file to read from:
Total Number of Lines: 10
Number of commented lines: 2
Maximum Length of commented lines: 19
Maximum Length of non-commented lines: 22
Commented line of maximum length: "//run prog1 "
Non-commented line of maximum length: " ///copy file1 file2"
1a2
Why am I getting the "1a2" at the end?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
