File I/O Question

Hi guys,

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.

Heres the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <fstream>
using namespace 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().
Yesssss!!!! Thank you so much man! Lol I'm excited right now :D
Topic archived. No new replies allowed.