I was writing a simple program at school, and I got stuck on reading text files. I know ... pathetic. :rolleyes: But I really don't know the correct syntax for this.

The program asks the user for a filename, opens it, and displays the content. My problem is that I don't know the correct syntax to use ifstream to open a file, with a filename that the user inputs. Basically, how do I tell it to read a file without using quotation marks ?

I was thinking along the lines of:

Code:

ifstream a_file (<<location<< );

// location bieng the string in which the filename & location are stored.

Not quite, I think it is lacking the code to close the existing stream before you open again. I am not sure of the effects of opening a stream before closing the existing failed stream, but explicitly closing it would be clearer anyway.

06-29-2006

Necrofear

So I just add an : a_file.close();

before opening again right ?

06-29-2006

laserlight

Yes.

06-29-2006

Necrofear

Cool, I got summthin' right for a change. :rolleyes:

Thankyou for all your time laserlight. It was most helpful.

EDIT: Sorry confused again.

Using that code, how would I tell it to read the whole text file ?
I noticed it's only reading up to the first space, or first newline.

06-29-2006

twomers

to read a whole text file this is what I do:

Code:

ifstream in ( "filename.txt" ); // stream

string WholeFile; // Where I want to store the whole file
string temp; // just a tempray thing for getting lines.

while ( getline( in, temp) ) // gets a line of the file and stores in temp
{
WholeFile += temp; // appends temp to the file string
WholeFile += "\n"; // appends a new line to the file string
}

in.close();// closes stream

or something along those lines. I have it as a function for simplicity.

06-29-2006

Tonto

Code:

while(i) s += i.get();

Or something where s is an std::string, i is the input file. This also works