Dec 21, 2012 at 9:59pm UTC
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;
}
Dec 21, 2012 at 10:04pm UTC
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 Dec 21, 2012 at 10:10pm UTC
Dec 21, 2012 at 10:23pm UTC
Thank You!
How would i get only the second line of the file?