Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created November 21, 2013 01:52
Show Gist options
  • Save dgodfrey206/7574773 to your computer and use it in GitHub Desktop.
Save dgodfrey206/7574773 to your computer and use it in GitHub Desktop.
Extracting the first and last name from a stream into variables
#include <iostream>
#include <string>
#include <locale>
#include <sstream>
template<
class charT,
class iter_type,
class string_iterator_type
>
void basic_get_name(iter_type beg, iter_type end, std::ios_base& str,
string_iterator_type it1, string_iterator_type it2)
{
auto ctypeFacet = &std::use_facet<std::ctype<charT>>(str.getloc());
typedef std::ctype_base base_type;
while (beg != end)
{
if (ctypeFacet->is(base_type::alpha | base_type::punct, *beg))
*it1++ = *beg;
else if (ctypeFacet->is(base_type::space, *beg))
{
if (ctypeFacet->is(base_type::alpha, *++beg))
{
while (ctypeFacet->is(base_type::alpha, *beg) && (beg != end))
*it2++ = *beg++;
break;
}
break;
}
++beg;
}
}
template<class charT>
void get_name(std::basic_istream<charT>& is, std::basic_string<charT>& first,
std::basic_string<charT>& last)
{
typedef std::back_insert_iterator<std::basic_string<charT>> str_iter;
typedef std::istreambuf_iterator<charT> iter_type;
basic_get_name<charT>(iter_type(is), iter_type(), is,
str_iter(first), str_iter(last));
}
int main()
{
std::istringstream ss("Stroustrup, Bjarne 8 8 -1 -1 -1");
std::string first, last;
get_name(ss, first, last);
std::cout << first << last; // Stroustrup, Bjarne
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment