Lesson 13: File Input / Output

[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)


[spoiler title=”Lesson Source Code”]

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(){
  // cout << "String" ;
  // cin >> variable;
  string fileName = "Text.txt";
  string fileName2 = "Text2.txt";
  string str = "";
  ofstream fout;
  ifstream fin;
  int wordCount = 0, lineCount=0;
  //getline(cin, str);
  while (fin >> str){
    if (str != "Bird"){
      fout << str << endl;
  /*while (getline(fin, str)){
    cout << str << endl;
  while (fin >> str){
    cout << str << endl;
  cout << "The number of words in this file was: " << wordCount << endl;
  //cout << "The number of lines in this file was: " << lineCount << endl;
  return 0;
Cat Dog Bird


Homework: Homework available here: http://beginnerscpp.com/forums/index.php/topic,73.0.html

File Input / Output
File input / output has been one of the most confusing topics for students. By the time they make their way to me they have tried slogging through assignments for hours. A few days ago I had a student approach me that spoke of working for 7 hours without being any closer to solving his solution. His code was a mess, and he was unable to explain how he had gotten to that point. So let me tell you before I even begin showing you code. There are differences between handling files and handling console input (via cin / cout) but for the most part, the two are VERY similar.

#include <fstream>
ifstream fin; //input filestream
ofstream fout; //output filestream
string str="";
fin >> str; //read once from the file until whitespace
getline(fin,str); //Read a line from the file until \n
fin.close(); //Close the file to free up memory
fout.open(fileName); //Open a file for output
fout << "The sum of 1+2 = " << 1+2;

As you can see in the above code, all we need to do to read a line or to read in a single word is EXTREMELY similar in syntax to the usage of cin / cout that you should be familiar with by now. To read an entire file in this manner, we just expand the single statements into a while statement:

while(getline(fin,str)) { //do line-by-line stuff here }
while(fin >> str ){ //do word-by-word logic here }