The following is the file(ka.txt) from which I want to read lines :-
ASD|BSD|CSdsa|ood
fmads|aok|pdski
kdijf|okmdsomf|opkasd|okd
asdas
kamkd|aoda|kked|ok
The following is the code that I've written to put this data into a vector of std::array<std::string, 4>.
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <fstream>
#include <sstream>
int main(){
std::fstream file("ka.txt");
std::vector<std::array<std::string, 4>> darr; darr.reserve(5);
std::array<std::string, 4> istd;
std::string * line = new std::string; std::string * word = new std::string;
while(std::getline(file, *line)){
std::stringstream ss(*line);
int per = 0;
while(!ss.eof()){
std::getline(ss, *&istd[per], '|');
per++;
}
darr.emplace_back(istd);
}
file.close();
for(int i = 0; i < darr.size(); i++){
for(int j = 0; j < 4; j++){
std::cout << darr[i][j] << "\t";
}
std::cout << "\n";
}
return 0;
}
Basically, I have a vector which has std::array
's and each std::array
is of size 4. So I am reading the data from the file with |
delimiter. And I want to store each element in every row of the text file as a std::array
. And storing these std::array
s in one vector. Also, if one row has 4 elements separated by |
, then there should be four elements in the std::array
. If there is only one element in the row, then there should be only one element in the std::array
So when I run this code I get the following output:-
ASD BSD CSdsa ood
fmads aok pdski
kdijf okmdsomf opkasd okd
asdas opkasd okd
kamkd aoda kked ok
So, the fourth row has a wrong std::array
since it should only have one element, but instead it should have only one. How can I achieve this?
Also, I think the probable problem is in the while
loop which begins at line 12 of the code.
Aucun commentaire:
Enregistrer un commentaire