Struggling to store the words in a 2D Array, when I use char It works fine but when I use the logic below for storing string that's where I got confused
Code:
string word;
int rows ,column;
string arr[10][20];
fstream myFile("name.txt");
while(myFile>>word)
{
arr[rows][column]=word;
}
Here I'm stuck that whats the algorithm for differentiation b/w rows and columns.
name.txt:
It's steve
Studying CPP
and steve loves cooking
Also, I want to display occurrences of this file as 2D-Array once I find the differentiation Algorithm
CodePudding user response:
You should use std::vector
instead of array because std::vector
is a variable size container and you don't always know how many elements the input.txt file contains. The complete working program below shows how to achieve what you want using 2D std::vector
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include<fstream>
int main() {
std::string line, word;
std::ifstream inFile("input.txt");
//create/use a std::vector instead of builit in array
std::vector<std::vector<std::string>> vec;
if(inFile)
{
while(getline(inFile, line, '\n'))
{
//create a temporary vector that will contain all the columns
std::vector<std::string> tempVec;
std::istringstream ss(line);
//read word by word
while(ss >> word)
{
//std::cout<<"word:"<<word<<std::endl;
//add the word to the temporary vector
tempVec.push_back(word);
}
//now all the words from the current line has been added to the temporary vector
vec.emplace_back(tempVec);
}
}
else
{
std::cout<<"file cannot be opened"<<std::endl;
}
inFile.close();
//lets check out the elements of the 2D vector so the we can confirm if it contains all the right elements(rows and columns)
for(std::vector<std::string> &newvec: vec)
{
for(const std::string &elem: newvec)
{
std::cout<<elem<<" ";
}
std::cout<<std::endl;
}
/*another way to print out the elements of the 2D vector would be as below
for(int row = 0; row < vec.size(); row)
{
for(int col = 0; col < vec.at(row).size(); col)
{
std::cout<<vec.at(row).at(col)<<" ";
}
std::cout<<std::endl;
}
*/
return 0;
}
The output of the above program can be seen here. At the end of my program i have printed out the elements of the 2d vector so that we can confirm if it contains all the elements correctly.
CodePudding user response:
Well, first of all, I think you forgot to initialize rows
and column
. But aside from that, string
s manage the character array on their own, so you don't need a 2D array for them, but a simple 1D one.
Like so:
string word;
int rows = 0;
string arr[10];
fstream myFile("name.txt");
while(myFile>>word)
{
arr[rows] = word;
rows ;
}