Login    New User    Forgot Password    Help      

Input

GO TO INDEX

Input

Recalling from the previous tutorial about the getline() function, input from text files are used in that fashion. Input of files also require the <string> library for the getline() function.

Here is an example of file input. The file must be created first in order for this to work.

Example

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
string line;

//the variable of type ifstream:
ifstream myfile ("example.txt");

//check to see if the file is opened:
if (myfile.is_open())
{
//while there are still lines in the
//file, keep reading:
while (! myfile.eof() )
{
//place the line from myfile into the
//line variable:
getline (myfile,line);

//display the line we gathered:
cout << line << endl;
}

//close the stream:
myfile.close();
}

else cout << "Unable to open file";

return 0;
}

This program will attempt to read a file for input, display the line you read and then close the file.

Here is some information about the new function eof() which stands for "end of file".

eof()

The eof() function is a boolean function that will check whether or not the file has reached the end. It returns true when the file is at the end and false otherwise.

GO TO INDEX