Solution : There are many solution for this problem I think. However, personally I like this one the most. Clean and Clear ! Enjoy and have fun :D
#include <iostream>
#include <stack>
#include <string>
typedef std::stack< std::string > scon;
void cut_string( const std::string& str, scon* sentence, const std::string& del )
{
std::string::size_type start = 0;
std::string::size_type end = str.find_first_of(del, start);
std::string::size_type length = str.length();
std::string word;
while( std::string::npos != end && end < length )
{
word = str.substr( start, end - start );
sentence->push( word );
start = end + 1;
end = str.find_first_of( del, start );
}
end = str.find_last_of( " " ) + 1;
sentence->push( str.substr( end ) );
}
void print_backward( scon* c )
{
while ( !c->empty() )
{
std::cout << c->top() << " ";
c->pop();
}
}
int main()
{
scon c;
std::string sentence;
std::cout << "Enter a sentence : \n";
getline( std::cin, sentence );
cut_string( sentence, &c, " " );
print_backward( &c );
return 0;
}
No comments:
Post a Comment