Sunday, May 22, 2011

c++ chomping white space

A Bit of code to chomp strings in c++

#include <string>
#include <iostream>

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

  std::cout << "'" << str << "'" << std::endl;
    
  std::string::size_type pos = str.find_last_not_of("\n \t");
  if(pos != std::string::npos) 
  {
    str = str.substr(0, pos+1);
  }
    
  std::cout << "'" << str << "'" << std::endl;
}

No comments:

Post a Comment