Given this string (or any string): "# ####\n# #\n# ## #\n# #\n### ##\n", how can I I'm working on a shortest path finding maze solver for my data structures and algorithms class. Given this string (or any string), how can I make a 2D array from it? That way, I can just loop through the 2d array and if its a whitespace, I can make a new vertex.
For example, this
"# ####\n# #\n# ## #\n# #\n### ##\n"
should be stored in the 2D array like so:
# ####
# #
# ## #
# #
### ##
I tried implementing this but it didn't print out the right thing.
char ** grid;
for(int i = 0; i < maze.size(); i++){
grid[i] = new char[numCols];
for(int j = 0; j != '\n'; j++){
cin >> grid[i][j];
}
}
Not sure that you deal with a fixed number of lines. The example below is conservative, it assumes that you do not know in advance the number of lines and that each line could have different length, hence it uses a vector of vector
of string
.
You can replace this with arrays if you know the size in advance. Comments should make the behavior clear.
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
const char *s = "# ####\n# #\n# ## #\n# #\n### ##\n";
istringstream is(s); // associate the input string with an input stream
vector<string> result; // use string for each line because a vector of characters is a string
string line;
while(getline(is, line)) // use stream library to read until next \n character
result.push_back(line); // add line
// demonstrate results
for (size_t i = 0; i < result.size(); ++i) {
for (size_t j = 0; j < result[i].length(); ++j)
cout << result[i][j];
cout << "\n";
}
return 0;
}