Simple I/O Example

Posted: November 13, 2010 in Uncategorized

Here is a program to output a text file out one word per line.  NOTE:   you must put your text file in the same directory as your .cpp files for this to work.

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main(void)
{
string fileName;
string wordBuffer;
ifstream file;

cout << “Please enter the file name to read: ” << endl;
cin >> fileName;

cout << “Start of file” << endl;

file.open(fileName.c_str());
if(! file.is_open()) {
cerr << “Error opening file: ” << fileName << endl;
exit(1);
}

while(! file.eof() )
{
file >> wordBuffer;
cout << wordBuffer << endl;
}

cout << “End of file” << endl;

system(“pause”);

return 0;

}

About these ads

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