lundi 20 janvier 2020

Comparing elements of text file

I am trying to compare blocks of four numbers with each other to make a new output file with only the ones that meet that: four digit numbers which have all digits the same.

This is my code for the input file:

int main() { ofstream outfile ("text.txt"); outfile << "1111 1212 4444 \n 2222 \n \n 8888 4567" <<endl;

I want to split this in blocks of four like "1111", "1212" and so on to be able to only write the ones that meet the requirement in the new output file. I decided to conver the whole file into an integer vector to be able to compare them.

   char digit;
   ifstream file("text.txt");
   vector <int> digits;

   while(file>>digit)
   {
      digits.push_back(digit - '0');
   }

and I suppose that the method that compares them would look something like this:

bool IsValid(vector<int> digits){

   for (int i=0; i<digits.size() i++)
   {
      if(digits[0] == digits[1] == digits[2] == digits [3])
         return true; 

      else 
      {
         return false;
      }
   }
}

However this would just compare the first block, would you do it differently? or should I keep doing the vector idea.

Aucun commentaire:

Enregistrer un commentaire