Answer to Question #75582 in C++ for Nik

Question #75582
Using txt file Horoscope for example, how would you create a file object and Load the file into a 2D vector: vector<vector<char>>
1
Expert's answer
2018-04-06T15:29:12-0400
#include <fstream>
#include <vector>

using namespace std;

int main()
{
// vector of line vectors
vector<vector<char>> array;

ifstream input_stream("Horoscope.txt"); // create file object

if (input_stream) // if the file object was successfully created
{
int line = 0; // line counter
array.push_back(vector<char>()); // add first empty line vector

char ch;

// get characters from the stream until EOF is reached
while (input_stream.get(ch))
{
array[line].push_back(ch); // add character to the end of the line vector

if (ch == '\n') // if newline encountered
{
++line; // increase line counter
array.push_back(vector<char>()); // add next empty line vector
}
}
}

return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS