mardi 14 janvier 2020

Comparing elements of text file between each other

I am trying to compare blocks of three numbers with each other to make a new output file with only the ones that meet that: first digit of the block is less than the second and less than the third, the second digit in the block has to be greater than the first but less than the third.

This is my code for the input file:

int main()
{
ofstream outfile ("test.txt");
outfile << "123 456 789 123 123 432 \n 123 243 " << endl;

I want to split this in blocks of three like"123", "456" and so on to be able to only write only 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("test.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[0] < digits[2] & digits[1]<digits[2])
    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