Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <algorithm>
- #include <vector>
- #include <string>
- constexpr auto str_end = std::string::npos;
- using std::vector;
- using std::string;
- using std::ostream;
- using std::ifstream;
- using std::getline;
- using std::cout;
- using std::endl;
- using std::stoi;
- using std::stod;
- // stream vector elements out
- template <typename T>
- ostream& operator<<(ostream& os, const vector<T>& vec) {
- for (const auto& elem : vec) os << elem << ' ';
- return os;
- }
- // Declare a generic conversion function...
- template <typename T>
- T decode(const string& x);
- template <>
- inline string decode(const string& x) {
- return x;
- }
- template <>
- inline int decode(const string& x) {
- return stoi(x);
- }
- template <>
- inline double decode(const string& x) {
- return stod(x);
- }
- // given a string with delimiters inside, parse it into
- // individual tokens stored in a vector<T>
- template <typename T>
- void tokenize(const string& str, vector<T>& tokens,
- const string& delimiters = " ") {
- auto last_pos = str.find_first_not_of(delimiters, 0); // first token
- auto curr_pos = str.find_first_of(delimiters, last_pos); // next delim
- while (curr_pos != str_end || last_pos != str_end) {
- // Add the extracted token after converting it to the proper type.
- tokens.emplace_back(decode<T>(str.substr(last_pos, curr_pos - last_pos)));
- last_pos = str.find_first_not_of(delimiters, curr_pos); // next token
- curr_pos = str.find_first_of(delimiters, last_pos); // next delim
- }
- }
- int main() {
- ifstream fs{"data"};
- string tmp{""};
- const string delims{"[,]"};
- // vector<string> tokens;
- // vector<int> tokens;
- vector<double> tokens;
- while (getline(fs, tmp)) tokenize(tmp, tokens, delims);
- cout << tokens << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement