How to read from a file in C++

by

This is a basic example how to read from a file in C++ without much error checking or anything. If you want to have a look at the ifstream reference, it’s here.

#include
#include
#include
using namespace std;
int main() {
ifstream file;
string line;
file.open(“./myfile.txt”);
if (!file.is_open()){
cerr << "Oops. Could not open file." << endl; return -1; } while (!file.eof()) { getline(file, line); cout << line << endl; } file.close(); } [/sourcecode]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: