I'm new to C++ programming and trying to figure out a weird line read behavior when reading a line from a text file. For this specific program, I have to wait for the user to press enter before reading the next line.
If I hard code the file name, the file read starts at line 1 as expected:
#include <iostream>
#include <fstream>
using namespace std;
int main(void) {
   ifstream in_file;
   in_file.open("test.txt");
   // read line by line
   string line;
   while (getline(in_file, line)) {
      cout << line;
      cin.get();
   }
   in_file.close();
   return 0;
}
I compile with g++ -Wall -std=c++14 test1.cpp -o test1 and get:
$ ./test
This is line one.
**user presses enter**
This is line two.
**user presses enter**
This is line three.
etc. etc.
But when I add in the option to have the user type in a file name, the line read starts at line 2:
#include <iostream>
#include <fstream>
using namespace std;
int main(void) {
   string filename;
   cin >> filename;   
   ifstream in_file;
   in_file.open(filename);
   // read line by line
   string line;
   while (getline(in_file, line)) {
      cout << line;
      cin.get();
   }
   in_file.close();
   return 0;
}
The same compile command gives me:
$ ./test2
test.txt
This is line two.
**user presses enter**
This is line three.
**user presses enter**
This is line four.
etc. etc.
Am I missing something here? I have no idea why it starts reading at line 2 when I add in the code to specify a file name. Am I not finishing the cin statement properly or something?
Thanks!
 
     
     
    