Sign in to follow this  

Boost Tokenizor

Recommended Posts

Hey, I have a std::string inputted by the user and I use the Boost Tokenizor to iterate through it. It is for a console so say the syntax of a command is LIGHT [ ON || OFF ] There is obviously an error however when someone just inputs LIGHT with nothing else after it. Here is my code:
  if(*Token_Iter == "LIGHT")
    if(*Token_Iter == "ON")
      Device->LightEnable(0, true);
    if(*Token_Iter == "OFF")
      Device->LightEnable(0, false);
So the error is caused at the ++Token_Iter; obviously but is there some way to handle this or do I have to check if the Pointer is valid (compare it to the end pointer?) every time? Thanks for your help, much appreciated [smile] Jemburula

Share this post

Link to post
Share on other sites
We probably have to see more code, but you should be checking that the iterator is not == end.

[edit] I don't think the error is with ++Token_Iter;. Rather, I think it is due to if(*Token_Iter == "ON") with Token_Iter at the end. How do you set up your Token_Iterator?

[edit2] Here is an example of how it should look like:
#include <iostream>
#include <string>
#include <boost/token_iterator.hpp>

int main() {
std::string s;
std::getline( std::cin, s );

typedef boost::token_iterator_generator< boost::char_separator< char > >::type TokenIter;
boost::char_separator< char > sep( " \t" );
TokenIter it = boost::make_token_iterator< std::string >( s.begin(), s.end(), sep );
TokenIter end = boost::make_token_iterator< std::string >( s.end(), s.end(), sep );

if( it != end ) {
if( *it == "LIGHT" ) {
if( ++it != end ) {
if( *it == "ON" )
Device->LightEnable(0, true);
else if( *it == "OFF" )
Device->LightEnable(0, false);
else {
std::cerr << "Invalid syntax: should be LIGHT [ ON || OFF ]" << std::endl;
else if( *it == "STATUS" ) { // et cetera, ad nauseam
std::cout << "Ughh, I don't feel good." << std::end;
else std::cerr << "Unknown command" << std::endl;
// Could give an error about no command,
// but what self-respecting command line would do that?

[Edited by - jflanglois on May 20, 2006 3:35:29 AM]

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this