Originally Posted by
matsp
There are some boost functionality that allows you to use C-style format strings to parse strings and/or input
I do not think so. There would be Boost.Regex and Boost.Spirit, but both would likely be overkill here. There is Boost.Format too, but that is for formatting output in a type safe manner yet using format strings.
Originally Posted by
brewbuck
iostreams would be more useful if it had the ability to match constant portions of the input.
hmm... I did not think of this before, even though something similiar is quite prevalent in Boost.Spirit. Perhaps it would make for a proposal to add a new manipulator to the C++0x standard library?
EDIT:
Okay, something cobbled together from my inspection of MinGW port of g++ source:
Code:
#include <string>
#include <memory>
#include <iostream>
template<typename charT, typename traits = std::char_traits<charT>,
typename allocator = std::allocator<charT> >
class match_token_
{
public:
match_token_(const std::basic_string<charT, traits, allocator>& token)
: token_(token) {}
const std::basic_string<charT, traits, allocator>& token() const
{
return token_;
}
private:
std::basic_string<charT, traits, allocator> token_;
};
template<typename charT, typename traits, typename allocator>
inline
match_token_<charT, traits, allocator>
match_token(const std::basic_string<charT, traits, allocator>& token)
{
return match_token_<charT, traits, allocator>(token);
}
template<typename charT>
inline match_token_<charT> match_token(const charT* token)
{
return match_token_<charT>(std::basic_string<charT>(token));
}
template<typename charT, typename traits, typename allocator>
std::basic_istream<charT, traits>&
operator>>(std::basic_istream<charT, traits>& in,
match_token_<charT, traits, allocator> matcher)
{
typename std::basic_string<charT, traits, allocator>::const_iterator
i = matcher.token().begin(),
end = matcher.token().end();
typename std::basic_istream<charT, traits>::char_type c;
while (i != end && in.get(c))
{
if (*i == c)
{
++i;
}
else
{
in.clear(std::basic_ios<charT, traits>::failbit);
break;
}
}
return in;
}
int main()
{
const std::string exclaim("!");
int a;
if (std::cin >> match_token("a=") >> a >> match_token(exclaim))
{
std::cout << "You entered: " << a << std::endl;
}
else
{
std::cerr << "Input error" << std::endl;
}
}