I'm relatively new to C++. I've been trying to make a program where it
asks you to input the name of a text file and spits the text of the file
out onto the screen.
#include <iostream>
#include <string>
#include <fstream>
usingnamespace std;
int main()
{
string lines;
// Asks what file you want to open
cout << "What file do you want to open? ";
string file;
// I dont really know what to do at this part...
fstream theFile (file);
// Tests to see if file exists and if it does
// it prints the text in the file to the screen
if (theFile.is_open())
{
while (!theFile.eof())
{
getline (theFile, lines);
cout << lines << endl;
}
theFile.close();
}
// If file was not found then this executes
else
{
cout << "The file could not be found..." << endl;
}
// I know this part is kinda poor
// but i'm just being lazy :D
system ("PAUSE>nul");
return 0;
}
I think its the fstream theFile (file); part thats not working. All help is most appreciated :D
That code would work fine, except you need to use file.c_str(), since fstreams only take char* as arguments. Also, you need to ask the user for the file name, preferably using getline().