Tag Archives: #WSQ11

Homework 11: Go Bananas

Now we are going to make a program that can find the quantity of BANANAS present in a text file. The word “banana” can be writen in any way, that’s why I opted for converting all letter in the document to lower case.

I set a vector called BANANA with a size of 6, where each position represent a letter of “banana” in the correct order. This is be very useful to find the wished words.

I also created a bool function, which counts the number of bananas . This function receives two parameters, one is a vector that contains charactesrs taken from the text file and another is its size.

I made the program to read character by character, convert them to lowercase, and if a character was a “b”, then we aply the function compare.

Of course, we have to open the text file, and then close it. I also implement that the program ask for a file to read.

This is my final code.

#include <iostream>
#include <ctype.h>
using namespace std;
#include <fstream>

bool compare(char vector_prueba[], int N=6)
{
  char BANANA[6]={'b','a','n','a','n','a'};
  bool result=true;
  int c=0;
  while(c<6)
  {
    if (BANANA[c]==vector_prueba[c]) c++;
    else return false;
  }
  return true;
}

int find_Bananas(string nombre)
{
    fstream ficheroEntrada;
    int Ban=0;
    char letra;

    ficheroEntrada.open ( nombre.c_str() , ios::in);
    if (ficheroEntrada.is_open()) {

        while (! ficheroEntrada.eof() ) {
          ficheroEntrada >> letra;
          letra = tolower(letra);
          if (letra == 'b')
          {
            char bananatest[6]={'b'};
            for(int i=1; i<6; i++)
            {
              ficheroEntrada >> letra;
              bananatest[i] = letra;
              bananatest[i] = tolower(bananatest[i]);
            }
          if (! ficheroEntrada.eof() ){ // evaluates if the file have finished (if there is no more to read)
             if (compare(bananatest,6)) Ban++;
           }
         }
        }

        ficheroEntrada.close();
    }
    else cout << "Fichero inexistente o faltan permisos para abrirlo" << endl;
    return Ban;
}
int main()
{
    string nombre;
    cout << "\n\nDime el nombre del fichero: ";
    getline(cin,nombre);
    cout << "\nThere is/are " << find_Bananas(nombre) << " banana's in the file.\n\n" << endl;

    return 0;
}