No number on file



  • We need to count a whole bunch of chips (unknown size) from a file, remembrance it and present it as a matrix. The code should be as compact as possible, so I decided not to count the data as a line and then convert it into numbers.

    int main() 
    {
    
    ifstream infile("array.txt");
    int n, counter = 0, **p;
    while (!infile.eof()) {
        counter++;
    }
    
    counter = sqrt(counter);
    cout << "counter is " << counter << endl;
    p = new int*[counter];
    
    for (int i = 0; i < counter; i++)
        p[i] = new int[counter];
    
    while (!infile.eof()) {
        for (int i = 0; i < counter; i++) {
            for (int j = 0; j < counter; j++)
                p[i][j] = n;
        }
    }
    for (int i = 0; i < counter; i++) {
        for (int j = 0; j < counter; j++) {
        cout << p[i][j] << " ";
        }
        cout << endl;
    }
    _getch();
    return 0;
    

    }

    Here's my code, it's made under a square matrix, as it hasn't yet found a better way to determine the size of the matrix. The problem is, for the first time, I'm conditional on the size of the mass, and for the second time, I can't count anything.



  • The chips are not read from the file because at the time of completion of the matrix, the end of the file is reached (when the size is calculated). Besides, there's no attempt to read any of the files. I think it's logical to assume that if there's a matrix in the file, it's got to be a N line and a M pole. So you can count the data from the file promptly. To avoid memorialization, a standard vector can be used as a repository for each line of the matrix and present the whole matrix as a vector of the same vectors. According to the http://www.cplusplus.com/reference/fstream/ifstream/ reading from ifstream can be done in different ways. It is possible to calculate the number immediately by means of the operator of the vent. You can get the line straight with help getline and evaporate it into the chiel vector.

    Under this approach, it will not be necessary to determine the size (not the fact that it will be the right thing to do in your case).




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2