Thursday, July 2, 2009

How to skip '\n' when working with number and char ?

Number and character are sometimes really annoying when being mixed together.
Simple trick could solve the problem :

#include <iostream>
#include <string>

template< typename charT >
class Skipper
{
public :
typedef charT char_type;
Skipper( char_type delim ):delim_( delim )
{ }
template< typename traits >
void operator ()( std::basic_istream< charT, traits >& ) const;
private :
char_type delim_;
};

template< typename charT >
template< typename traits >
void Skipper< charT >::operator ()( std::basic_istream< charT, traits >& stream ) const
{
char_type c;
while ( stream.get( c ) && c != delim_ )
;
}


template< typename charT, typename traits >
std::basic_istream< charT, traits >& operator >>( std::basic_istream< charT, traits >& stream,
const Skipper< charT >& f )
{
f( stream );
return stream;
}

template< typename charT >
Skipper< charT > skip( charT c )
{
return Skipper< charT >( c );
}

int main()
{
int x, y;
char c[ 10 ];
std::string next;


std::cout << "Please enter a number : \n";
std::cin >> x >> skip( '\n' );

std::cout << "Then, please enter a character : \n";
std::cin.getline( c, 10 );

std::cout << " RESULT IS : \n";

std::cout << x << "\n";
std::cout << c << "\n";
return 0;
}

No comments:

Post a Comment