Search code examples
c++fileifstream

How to hold place when reading a file in C++?


My infile.txt reads:

January 31
February 28
March 31
April 30
May 31
June 30
July 31
August 31
September 30
October 31
November 30
December 31

I need to create two functions: one that collects each month from the file (one month at a time), and another that collects the number of days in each month. This is what I have so far:

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

string read_month_name();
int read_num_days();

int main() {
  string month_name;
  int num_of_days;

  ifstream myfile;
  myfile.open("infile.txt");

  for ( int i = 0; i < 12; ++i ) {
      month_name = read_month_name();
      num_of_days = read_num_days();
      cout << "There are " << num_of_days << " days in " << month_name << ".\n";
  }
}

string read_month_name() {
  string month;
  ifstream myfile;
  myfile.open("infile.txt");
  myfile >> month;
  return month;
}

int read_num_days() {
  int days;
  ifstream myfile;
  myfile.open("infile.txt");
  myfile >> days;
  return days;
}

The problem is that every time I read the file, I only ever collect "January"; as both a string and an integer. Therefore my output looks like this:

  There are 0 days in January.
  There are 0 days in January.
  There are 0 days in January.
  There are 0 days in January.
  There are 0 days in January.
  There are 0 days in January.
  There are 0 days in January.
  There are 0 days in January.
  There are 0 days in January.
  There are 0 days in January.
  There are 0 days in January.
  There are 0 days in January.

Is there a way I can insert a placeholder in my infile.txt so that I always pick up reading where I left off?

P.S. I know that I can solve this by reading from the file in the main() function instead of in subprograms, but I need to find a way to make it work with the two subprograms.


Solution

  • Thanks for all the help, but the answer was a lot more simple than I thought. I simply needed to declare myfile outside of the main function and only open the file once inside of the main function. The problem was that I opened my file in the main function and in each subfunction. The code below functions exactly as I need it to:

    #include <iostream>
    #include <fstream>
    #include <iomanip>
    using namespace std;
    
    string read_month_name();
    int read_num_days();
    
    ifstream myfile;
    
    int main() {
      string month_name;
      int num_of_days;
    
      myfile.open("infile.txt");
    
      for ( int i = 0; i < 12; ++i ) {
          month_name = read_month_name();
          num_of_days = read_num_days();
          cout << "There are " << num_of_days << " days in " << month_name << ".\n";
      }
    }
    
    string read_month_name() {
      string month;
      myfile >> month;
      return month;
    }
    
    int read_num_days() {
      int days;
      myfile >> days;
      return days;
    }