0

I'm trying to draw an LCS table. And this part of my code stop after the first iteration of the inner while loop of the fill_the_table() function. I can't find what's wrong in my code. I'm new to C++ by the way...

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

#define U 1
#define L 2
#define UL 3

void fill_the_table(ifstream& file1, ifstream& file2, int **table, int **p){
  table[0][0]=0;
  p[0][0]=UL;
  string line1, line2;
  int i=1, j=1;

  file1.clear();
  file1.seekg(0, ios::beg);
  file2.clear();
  file2.seekg(0, ios::beg);

  while(getline(file1, line1)){
    table[0][j]=0;
    p[0][j]=L;
    while(getline(file2, line2)){
      table[i][0]=0;
      p[i][0]=L;
      if(line1==line2){
        table[i][j]=table[i-1][j-1]+1;
        p[i][j]=UL;
        i++;
      }
      else{
        if(table[i-1][j]>table[i][j-1]){
          table[i][j]=table[i-1][j];
          p[i][j]=U;
        }
        else{
          table[i][j]=table[i][j-1];
          p[i][j]=L;
        }
        i++;
      }
      j++;
    }
  }
  cout<<table[i][j];
  return;
}


void table(ifstream& file1, ifstream& file2){
  int i=0, j=0;
  string line1, line2;

  while(getline(file1, line1)){
    i++;
  }
  while(getline(file2, line2)){
    j++;
  }

  int** table = new int* [i];
  for(int a=0; a<i; a++){
    table[a] = new int [j];
  }
  int** p = new int* [i];
  for(int a=0; a<i; a++){
    p[a] = new int [j];
  }

  fill_the_table(file1, file2, table, p);

  for(int a=0; a<i; a++){
    delete[] table[j];
  }
  delete table;

  for(int a=0; a<i; a++){
    delete[] p[j];
  }
  delete p;

  return;
}

int main(int argc, char* argv[]){
  ifstream file1(argv[1]);
  ifstream file2(argv[2]);
  table(file1, file2);

  return 0;
}
  1. Can I pass the int** table and int** p the way I passed it from table() to fill_the_table()?
  2. Someone suggest me use vector<string> instead of reading the files themselves, which one is preferable?
Tom Ân
  • 1
  • 1
  • 1
    You read one line from `file1`, then completely exhaust `file2`. Then you read another line from `file1`, and then try to read from `file2` some more - but it's already at end-of-file. This is why the inner loop only runs once. – Igor Tandetnik Oct 06 '15 at 05:23
  • That might be one problem... But that would only be a problem after I completely exhaust file 2... I mean, when I run my program... It stop right after the first iteration of the inner while... It doesn't even get the second line of file2... – Tom Ân Oct 06 '15 at 05:58
  • If you keep re-reading the files, some manner of caching is recommended. File IO is painfully slow. Vector of string has benefits in simplicity. – user4581301 Oct 06 '15 at 06:53

0 Answers0