ifstream Need to read from file and output what's in it

Need the program to be able to find the .txt file, open it and read strings/what's in it. Then I have to printout out what is inside the file.

ex: myFile.txt
contains:
Line 1 : my dog
Line 2 : Im not going to school today
Line 3 : I hate going to class

The program output should be as follow:

my dog
Im not going to school today
I hate going to class

Here is the code that I have, but I get some weird errors and dont know how to fix it.

-------------------------------------------------

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

int main ()
{
string open_myFile;
cout << "Enter the name of an existing file: " << flush;
getline( cin, open_myFile );

ifstream file ( open_myFile );
file.open ();

if ( file.is_open() )
{
while ( file.good() )
{
cout << (char) file.get();
}
file.close();
}
else
{
cout << "Error opening file";
}

system ("pause");
return 0;
}
Last edited on
ifstream when you create an object of it as ifstream file(); then requires you to open it, file.open( filename ).
But if you put the filename in the declaration then it automatically opens it.
ifstream file( filename ).

It also requires a cstring and you are passing a string, which is why it won't work. There is however a string function to convert.
 
ifstream file ( open_myFile.c_str() );
Last edited on
I was able to fix it as shown below...thanks for all your help

---------------------------------------------------------------------------------------




/* This program will allow a user to enter a name of a file either
a txt, dat, or any type of file. Then once this file name is
entered by user, then the (ofstream myfile;) will allow you to
save it. Then the user get to input stuff into the file and
save everything in the text.
*/

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cstring>

using namespace std;

int main ()
{
char open_myFile[16]; //this will allow the file name be 16 in length
cout << "Enter the name of an existing file: " << flush;//
cin.getline ( open_myFile,17 ); //this will allow a string to be enter of length 16

// ***************************************************** //these lines below will allow for file to be open & cout content of file
ifstream file; //declares name "file" as ifstream
file.open ( open_myFile ); //this line open the file named: open_myFile
if (file.is_open()) //if file open then executes (.is_open() means if file opens fine)
{
while (file.good()) //while file is good (.good)
cout << (char) file.get(); //gets all characters/strings in file with get ( .get() )
file.close(); //closes file after it has cout everything in it
}
else
{
cout << "Error opening file";
}
// *****************************************************


cout << "\n\n\n";
system ("pause");
return 0;
}
Topic archived. No new replies allowed.