tags:

views:

652

answers:

3

Hi

Just wonder, for a matrix stored in a file as what it is, i.e. each line in the file being a row of the matrix where elements are separated by space(s), how can I predetermine the size of the matrix, then create an array of the same size and read it into the array in C and C++? If you have some code example, that would be appreciated!

Thanks and regards!

+5  A: 

Something like this. You need to include vector, sstream and string.

There is no need to find out the size of the vector in advance.

std::vector<int> readRow(std::string row) {
  std::vector<int> retval;
  std::istringstream is(row);
  int num;
  while (is >> num) retval.push_back(num);
  return retval;
}

std::vector<std::vector<int> > readVector(std::istream &is) {
  std::string line;
  std::vector<std::vector<int> > retval;
  while (std::getline(is, line))
    retval.push_back(readRow(line));
  return retval;
}
hrnt
+1  A: 

In C you might use fgets to read one line at a time, and strtok or similar to process the lines and atof or sscanf to read the numbers. The first line can be processed to determine the matrix width and allocate memory, then re-processed to insert the first row. If the height may be different then you would either need to dynamically allocate the memory, or read the whole file counting lines then reprocess it.

Timothy Pratley
+1  A: 

Read the first row, count the fields and then use fseek() to go back to the start of the file.

Aaron Digulla