Last active
March 26, 2022 16:40
-
-
Save dgodfrey206/4705b2401244266b1bee to your computer and use it in GitHub Desktop.
Word inserter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
#include <algorithm> | |
template<class charT> | |
struct word_inserter_impl { | |
word_inserter_impl(int words, std::basic_string<charT>& str, charT delim) | |
: str_(str) | |
, delim_(delim) | |
, words_(words) | |
{ } | |
friend std::basic_istream<charT>& | |
operator>>(std::basic_istream<charT>& is, const word_inserter_impl<charT>& wi) { | |
typename std::basic_istream<charT>::sentry ok(is); | |
if (ok) { | |
std::istreambuf_iterator<charT> it(is), end; | |
std::back_insert_iterator<std::string> dest(wi.str_); | |
while (it != end && wi.words_) { | |
if (*it == wi.delim_ && --wi.words_ == 0) { | |
break; | |
} | |
dest++ = *it++; | |
} | |
} | |
return is; | |
} | |
private: | |
std::basic_string<charT>& str_; | |
charT delim_; | |
mutable int words_; | |
}; | |
template<class charT=char> | |
word_inserter_impl<charT> word_inserter(int words, std::basic_string<charT>& str, charT delim = charT(' ')) { | |
return word_inserter_impl<charT>(words, str, delim); | |
} | |
struct Record { | |
int id; | |
std::string name; | |
int age; | |
}; | |
std::stringstream ifs("1 joe biden 55 00000000"); | |
int main() { | |
Record actRecord; | |
while (ifs >> actRecord.id >> word_inserter(2, actRecord.name) >> actRecord.age) { | |
std::cout << actRecord.id << " " << actRecord.name << " " << actRecord.age << '\n'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment