I'm working on a function that reads in lines of a file until the line "XXX" is reached in the file, and a counter keeps track of how many lines have been read. Then the program counts the remaining number of lines in the file. I'm using an if statement to determine when to break the while loop (when the line read equals "XXX") and the condition is not being met. Even when line == "XXX", the else statement will still run. What's wrong with my code? Thanks!
#include <string>
#include <iostream>
#include <fstream>
using std::string;
using std::endl;
using std::cout;
using std::ifstream;
int main()
{
//Main function
}
void read_file(string input_file_name)
{
string i_filename = input_file_name;
ifstream infile;
infile.open (i_filename);
string line;
int num_of_terms1 = 0;
int num_of_terms2 = 0;
if (!infile)
{
cout << "Your input file could not be opened."<<endl;
}
else
{
while (!infile.eof())
{
getline(infile, line);
cout << line << endl;
if (line == "XXX")
{
break;
}
else
{
cout << line << endl;
num_of_terms1++;
}
}
while (!infile.eof())
{
getline(infile, line);
cout << line << endl;
num_of_terms2++;
}
}
cout << "Terms 1: "<<num_of_terms1 <<endl;
cout << "Terms 2: "<< num_of_terms2 <<endl;
infile.close();
}
Here's a sample input file, inputfile.txt:
-2 3
4 2
XXX
-2 3
Thanks in advance for your help!