Writing a text file:
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else
{
cout << "Unable to open file";
}
return 0;
}
Reading a text file:
Reading one ''word'' at a time:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream myReadFile;
myReadFile.open("text.txt");
string word;
if (myReadFile.is_open()) {
while (myReadFile >> word) {
cout << word << endl;
}
myReadFile.close();
}
else
{
cout << "Unable to open file";
}
return 0;
}
OR
Reading one ''line'' at a time:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else
{
cout << "Unable to open file";
}
return 0;
}
Back to top