-3

I want to read following file in C++.

000001011100110
100000010101100
001001001001100
110110000000011
000000010110011
011000110101110
111010011011110
011001010010000

I know already how many rows and columns is there in the file. I want to read each integer and store it in a 2-D matrix of ints. Each integers here means 0 is one entry and 1 is another entry. So in this example above there are 15 0's and 1s.

Avinash
  • 11,749
  • 27
  • 102
  • 175

3 Answers3

1
int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << endl;
      int lineNumber;
      stringstream(line) >> lineNumber;
      //Do smith with this line read amount of digits
      int tempNumber = lineNumber;
      num_digits = 0;
      //get number of digits
      while(tempNumber > 0) {
         num_digits++;
         tempNumber/=10;
      }
      //print digits
      std::stringstream tmp_stream;
      tmp_stream << tempNumber;
      for (i = 0; i < tmp_stream.str().size(); i++)
      {
          std::cout << "Digit [" << i << "] is: " << tmp_stream.str().at(i) << std::endl;
      }
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

//get number of digits is some extra, maybe you will fond a better way of getting digits, so this could be useful

exactly for your purpose only this is needed:

if (myfile.is_open()){
    int line = 0;
    while ( getline (myfile,line) )
        {
          cout << line << endl;
          for (i = 0; i < line.size(); i++)
          {
              std::cout << "Digit [" << i << "] is: " << line.at(i) << std::endl;
              int lineDigitNumber;
              stringstream(line) >> lineDigitNumber;
          }
    line++;

    //Fill array with line and i
    }
    myfile.close();
}
1
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

const size_t NROWS = /* number of rows */;
const size_t NCOLS = /* number of cols */;

int main () {
  vector<vector<int> > myvec (NROWS, vector<int>(NCOLS));
  ifstream myfile ("example.txt");
  if (myfile.is_open ())
    {
      string line;
      for (size_t rowcount = 0; rowcount < NROWS && getline (myfile, line);
       ++rowcount)
    {
      size_t colcount = 0;
      for (string::const_iterator it = line.begin ();
           it != line.end () && colcount < NCOLS; ++it, ++colcount)
        {
          myvec[rowcount][colcount] = *it - '0';
        }
    }
      myfile.close ();
    }

  else
    cerr << "Unable to open file" << endl;

  return 0;
}

One of the neat things about std::vector<T> is that the constructor (size_t, T& default_value = T()) both preallocates and assigns. Hence, it is very easy to make a multidimensional array with it - just nest the vectors as needed, and nest (n-1) levels for the second argument.

R. Martinho Fernandes
  • 209,766
  • 68
  • 412
  • 492
moshbear
  • 3,162
  • 1
  • 17
  • 32
  • If `myfile.good()` returns true, it doesn't mean that reading will succeed. Here's an explanation: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong/5605159#5605159 (The question mentions `eof()`, but the same problems apply). It wouldn't fail for *this particular example*, though. – R. Martinho Fernandes Nov 18 '11 at 09:01
0

Here's my "exercise" with a quick'n'dirty matrix class implementation ;)

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

class CMatrix {

public:

    CMatrix(unsigned int r, unsigned int c)
    : rows(r), cols(c), a(new int [r*c])
    {}

    // copy constructor and copy assignment operator come here

    ~CMatrix()
    {
        delete [] a;
    }

    int& at(unsigned int r, unsigned int c)
    {
        if (r >= rows || c >= cols) throw std::out_of_range("Out of range access");
        return a[r*cols + c];
    }

private:

    unsigned int rows;
    unsigned int cols;
    int* a;

};


int main()
{
    // assuming the sample file OP provided
    const unsigned int n_rows = 8;
    const unsigned int n_cols = 15;

    std::ifstream myfile("in.txt");

    if (!myfile.is_open()) {
        // report error
    } else {

        CMatrix matrix(n_rows, n_cols);
        std::string line;
        unsigned int m = 0;
        unsigned int n = 0;

        while (getline(myfile, line))
        {
            n = 0;
            for (char& c : line) {
                matrix.at(m,n) = c == '0' ? 0 : 1;
                ++n;
            }
            ++m;
        }
    }
}
jrok
  • 51,107
  • 8
  • 99
  • 136