My assignment is to get a user input for the name of a file, read each line of the file, and then output how many valid and invalid command lines there are. I've been trying to do this efficiently but I keep getting confused so I just used brute force and basically spelled out each word. I know there is a way to do this more efficiently but I don't know how to do it. This is what I have:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream inputFile;
string filename;
string line;
int count = 0;
int comment = 0;
int len = 0;
int i = 0;
int run_lines=0,print_lines=0,copy_lines=0,delete_lines=0,invalid=0;
cout << "Enter the name of a file to read from: " << endl;
cin >> filename;
inputFile.open(filename);
if (!inputFile){
cout << "File cannot be opened " << filename << endl;
exit(1);
}
while(!inputFile.eof()){
getline(inputFile,line);
count++;
len=line.size();
for(i=0;i<=len;i++){
if(line[i]=='%'){
comment++;
}
else if(line[i]=='r'&&line[i+1]=='u'){
run_lines++;
}
else if(line[i]=='p'&&line[i+1]=='r'&&line[i+2]=='i'&&line[i+3]=='n'&&line[i+4]=='t'){
print_lines++;
}
else if(line[i]=='c'&&line[i+1]=='o'&&line[i+2]=='p'){
copy_lines++;
}
else if(line[i]=='d'&&line[i+1]=='e'&&line[i+2]=='l'){
delete_lines++;
}
}
}
inputFile.close();
cout << "\nTotal lines: " << count << endl;
cout << "Commented lines: " << comment << endl;
cout << "Valid Command lines: " << run_lines + print_lines + copy_lines + delete_lines << endl;
cout << "Invalid Command lines: " << invalid << endl;
cout << "Run commands: " << run_lines << endl;
cout << "Print commands: " << print_lines << endl;
cout << "Copy commands: " << copy_lines << endl;
cout << "Delete commands: " << delete_lines << endl;
return 0;
}
If someone can help me use the getline() function properly so that it loops through each line and reads the first word of each line of the file and then if the word matches any of the commands listed below such as "print", "delete", "copy", and "run" I would be very grateful. The code I have below compiles and works for some of the test cases but not all for obvious reasons. Please help me!