C++: Parse input skipping whitespace

Still re-reading Stroustrup's book, I found something I'd like to have known some time ago: an elegant way to parse an input stream for words separated by whitespace (1 whitespace = any amount of consecutive space and/or tabs). This can be done using an istream_iterator, like so:

#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>

void main(){

   using std::cout;
   using std::endl;
   // We read from standard input, but it could just as well be a file
   std::istream_iterator<std::string> ii( std::cin );
   cout << "--->Input whitespace-separated words:" << endl;
   
   // Suppose we stop reading when we find the word "END"
   std::vector<string> words;
   while ( *ii != "END" ){
      cout << *ii << endl;
      words.push_back(*ii);
      ii++;
   }
   
   // Sort words
   cout << "Sorted words:" << endl;
   sort( words.begin(), words.end() );
   for( unsigned int i = 0; i < words.size(); i++ )
      cout << words[i] << endl;
}

Comments

Popular posts from this blog

VB.NET: Raise base class events from a derived class

Apache Kafka - I - High level architecture and concepts

Upgrading Lodash from 3.x to 4.x