Tag Archives: #WSQ09

Homework 9: Multipart data and files

In this asingment we are going to read a text file and count the number of both lines and characters present on the document.

We need to use the libraries #include and #include to be able to use the functions that open and read text documents.

This is my code.

#include 
#include 
using namespace std;

int main()
{
  fstream text1;
  int lines=0, chars=0; // we initialize two variables for lines and characters, to count them
  string line; //we declare and string variable to read a line
  char letter; // this is gonna let us read each character

  text1.open("Archivo.txt", ios::in); // the file is open
  while(! text1.eof()) // reads each line and counts it
  {
    getline(text1,line);
    lines++;
  }
  text1.close();
  fstream text2;
  text2.open("Archivo.txt", ios::in); // the file is open
  while (! text2.eof() ) { // reads each character and counts it. 
    text2 >> letter;
    chars++;
  }
  text2.close(); // close the file
  lines-=1;
  chars-=1;

  cout << "\nThe file contains ... \n" << endl;
  cout <<"Amount of lines: " << lines << endl;
  cout <<"Amount of characters: "<< chars << endl << endl;



  return 0;
}