Is it possible to combine an istream_iterator with an regex_token_iterator similar like this:
std::copy(std::sregex_token_iterator(std::istreambuf_iterator<char>{ifs}, std::istreambuf_iterator<char>{}, r, 1), std::sregex_token_iterator{}, std::ostream_iterator<std::string>(std::cout));
To give this a little bit of context. Im new to programming and im trying to solve a problem where i want to delete everything in an ifstream, except digits. Im doing this for practice and learning.
The input file is looking like this:
aoisdnf 2 aopsjmdf 4 anpoidsnian 5 ainsdf 12 paalknshndf 43 aoksjhndfal 4 aslkdfoo 9 hjalkgshgdfk 4
The solution should look like this:
2 4 5 12 43 4 9 4
My first approach was this:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <ctype.h>
int main()
{
std::ifstream ifs ("C:/Users/../whitespace_seperated_integers.txt", std::ifstream::in);
std::string tmp;
std::vector<int> vector;
for (auto it = std::istreambuf_iterator<char>{ifs}; it != std::istreambuf_iterator<char>{}; ++it) {
if (*it >= '0' && *it <= '9') tmp.append(1, *it);
else if (!tmp.empty()){
vector.push_back(std::stoi(tmp));
tmp.clear();
}
}
if (!tmp.empty()) vector.push_back(std::stoi(tmp));
for(const auto i : vector){
std::cout << i << " ";
}
Which worked fine, but then i had the idea to solve this problem with regex, which lead to this solution:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <ctype.h>
#include <regex>
int main()
{
std::ifstream ifs ("C:/Users/../whitespace_seperated_integers.txt", std::ifstream::in);
std::string puf;
std::vector<std::string> vector;
std::string line;
char wts = ' ';
while(getline(ifs ,line, wts)){
puf += line;
}
std::regex r(R"([^\d]*(\d+))");
std::copy(std::sregex_token_iterator(puf.begin(), puf.end(), r, 1), std::sregex_token_iterator(), std::back_inserter(vector));
std::vector<int> vec;
std::smatch sm;
while(std::regex_search(puf, sm, r))
{
vec.push_back(std::stoi(sm[1]));
/* std::cout << sm[1] << '\n';*/
puf = sm.suffix();
}
for(const auto i : vec){
std::cout << i << " ";
}
}
But im not really happy with this code, so i was trying to figure out how to improve it. I tried to combine the istream_iterator with the regex_token_iterator, but im not able to figure out how it works.
Aucun commentaire:
Enregistrer un commentaire