Thursday, December 13, 2012
C++ TUTORIAL FOR BEGINNERS: How to read a file and store the records in a string
The program works as follows:
- openbook.txt must have records to read input from
- the program opens the input file for reading
- while condition is used to keep on reading while it's not yet end of the file
- if a record is read, the getline command is used to store in string record
- cout command is used to display on the screen the record read
Source code:
#include<iostream>
#include <string>
#include<fstream>
using namespace std;
int main()
{
string record;
ifstream inputfile;
inputfile.open("openbook.txt");
if (inputfile.is_open())
{
while (!inputfile.eof())
{
getline(inputfile, record);
cout << record << endl;
}
}
inputfile.close();
return 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment