I have the following file "maze.in" and I need to input this file such that it assigns values to six variables and load values into matrix (matrix[][]). The text file is:
1 2 3 4 5 6 7 8 9 10
10 7
0 8
5 9
xxxxxxxx x
x x x x
x x x x xx
x x x
x xxxxxx x
x x
xxxxxxxxxx
#include <fstream>
#include <iostream>
#include <sstream>
#include <limits>
#include <string>
#include <vector>
void waitForEnter();
int main()
{
std::ifstream infile("maze.in");
std::string line;
std::getline(infile, line); // gets rid of '\n'
std::stringstream iss(line);
int n {}, m {};
iss >> n >> m; // if you called it 'cols' and 'rows', you'd make less errors
// Problem: declaring a 2-D C-style array
// Option 1 (the best): use std::vector and get rid of every problems
std::vector<std::vector<int>> matrix (m, std::vector<int>(n));
// Option 2:
int* matrix2 = newint[m*n] {}; // all memory in subsequent cells
// Option 3:
int** matrix3 = newint*[m] {};
for(int i{}; i<m; ++i) {
matrix3[i] = newint[n] {}; // every 'row' could lie in different memory areas
}
// Let's read the other two lines of numbers, whatever they mean
std::getline(infile, line);
iss.str(line);
int startX {}, startY {};
iss >> startX >> startY;
std::getline(infile, line);
iss.str(line);
int endX {}, endY {};
iss >> endX >> endY;
for (int i=0; i < m; i++) {
std::getline(infile, line);
for (size_t j=0; j < line.length(); j++) {
matrix.at(i).at(j) = line.at(j);
matrix2[i*n+j] = line.at(j);
matrix3[i][j] = line.at(j);
}
}
infile.close();
// let's check if we've read everything correctly:
std::cout << "\nstd::vector:\n";
for(constauto& v : matrix) {
for(constauto i : v) { std::cout << char(i) << ' '; }
std::cout << '\n';
}
std::cout << "\nsingle pointer:\n";
for (int i=0; i < m; i++) {
for (int j=0; j < n; j++) {
std::cout << char(matrix2[i*n+j]) << ' ';
}
std::cout << '\n';
}
std::cout << "\npointer to pointer:\n";
for (int i=0; i < m; i++) {
for (int j=0; j < n; j++) {
std::cout << char(matrix3[i][j]) << ' ';
}
std::cout << '\n';
}
// Let's get to the hard job: avoid memory leaks:
// matrix: <-- will be correctly terminated by its destructor
delete[] matrix2;
for(int i{}; i<m; ++i) { delete[] matrix3[i]; }
std::cout << '\n';
waitForEnter();
return 0;
}
void waitForEnter()
{
std::cout << "\nPress ENTER to continue...\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::vector:
x x x x x x x x x
x x x x
x x x x x x
x x x
x x x x x x x x
x x
x x x x x x x x x x
single pointer:
x x x x x x x x x
x x x x
x x x x x x
x x x
x x x x x x x x
x x
x x x x x x x x x x
pointer to pointer:
x x x x x x x x x
x x x x
x x x x x x
x x x
x x x x x x x x
x x
x x x x x x x x x x
Press ENTER to continue...