Let's consider you have a file called "Pet Sematary.txt" and you have the following quote inside
The soil of a man's heart is stonier, Louis.
A man grows what he can, and he tends it.
'Cause what you buy, is what you own.
And what you own... always comes home to you.
which you want to read line by line and character by character and save to a vector of vectors of char.
#include <fstream>
#include <iostream>
#include <vector>
#include <iterator>
#include <iomanip>
int main() {
std::ifstream is("Pet Sematary.txt");
if (!is) {
std::cout << "Unable to open file!\n";
}
std::vector<std::vector<char>> grid;
for (std::istreambuf_iterator<char> beg(is), end; beg != end; ++beg) {
std::vector<char> tmp;
while (beg != end && *beg != '\n') {
tmp.emplace_back(*beg++);
}
grid.emplace_back(tmp);
}
for (auto const& line : grid) {
for (auto const ch : line) {
std::cout << std::setw(2) << ch;
}
std::cout << '\n';
}
return 0;
}
Define the ifstream object is and open the given file. Check whether the file exists and If it doesn't print an appropriate message. Define your grid. Loop through the file with istreambuf_iterators. Define the vector tmp which will represent the line you are processing. While the character you are reading isn't end of line grow tmp. When the character you read was end of line '\n' increment beg via for's ++beg to prepare beg for the next line. Grow grid this way until you read end-of-file.
When you print grid you will get this:
T h e s o i l o f a m a n ' s h e a r t i s s t o n i e r , L o u i s .
A m a n g r o w s w h a t h e c a n , a n d h e t e n d s i t .
' C a u s e w h a t y o u b u y , i s w h a t y o u o w n .
A n d w h a t y o u o w n . . . a l w a y s c o m e s h o m e t o y o u .