views:

65

answers:

1

Hiya.

I'm trying to read a file line by line to a string type variable using the following code:

#include <iostream>
#include <fstream>


ifstream file(file_name);

if (!file) {
    cout << "unable to open file";
    exit(1);
}

string line;
while (!file.eof()) {
    file.getline(line,256);
    cout<<line;
}
file.close();

it won't compile when I try to use String class, only when i use char file[256] instead.

how can I get line by line into a string class?

thanks!

+4  A: 

Use std::getline:

std::string s;
while (std::getline(file, s))
{
    // ...
}
James McNellis
7 seconds...fine. :p
GMan
thanks! i was missing the using namespace std.
ufk
@ufk: No, you were using the `istream::read` member function; you need to use the `std::getline` function, which is not a member function.
James McNellis
thanks for the quick and full assistance!! :)
ufk