Trouble getting line of file

I am trying to get the first line of the file and I'm not getting any part of the file.

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

int main ()
{
string filename;
cout << "Enter password file: ";
getline( cin, filename );
fstream file( filename.c_str() );
if (!file)
{
cerr << "Unable to Open Input File: "
<< filename << "\n";
return 0;
}
else
{
ifstream file;
string line1="";
while(getline(file, line1))
{
cout<<line1<<endl;
}
}
return 0;
}
The file stream can not read anything from the file because it has yet to receive the name of the file that is to be opened. I've also noticed that both of the objects created have the same identifier (file and file). The code posted below should correctly perform the given task.

1
2
3
4
5
6
7
8
9
10
string filename;
getline(cin, filename);
ifstream file(filename);
if(!file) {
     cerr << "Error: Unable to open file.\n";
     return -1;
}
string line1;
getline(file, line1, '\n');
cout<<line1<<endl;
Last edited on
Thank You!

How would i get only the second line of the file?
Topic archived. No new replies allowed.