making words backwards

Started by
4 comments, last by DigitalDelusion 19 years, 6 months ago
I was just wondering how do you make a program that you type in a word and then it prints it backwards.
Advertisement
someone just wrote a program on the lounge to do exactly that, the simplest way is with recursion, though it wouldn't be very hard to do with the standerd string libraries.
you mean something like this?

void reverse( std::string& str ){	const size_t str_size = str.size();	const size_t loops_required = str_size / 2;	for ( size_t i = 0; i < loops_required; ++i )	{		std::swap( str, str[ str_size - i - <span class="cpp-number">1</span> ] );<br>	}<br>}<br><br><br></pre></div><!–ENDSCRIPT–> 
Uh, no.
void reverse_string(const std::string & src, std::string & dest){  dest = src;  std::reverse(dest.begin(), dest.end());}
Actually, if you are going to reverse copy, you should really use the correct algorithm so the semantics convey the proper intent:
void reverse_string(const std::string & src, std::string & dest){	dest.resize(src.length());	std::reverse_copy(src.begin(), src.end(), dest.begin());}
std::string s;std::cin >> s;std::copy( s.rbegin(), s.rend(), //print it backwards to coutstd::ostream_iterator<std::string::value_type>( std::cout));//alternative waystd::reverse_copy( s.begin(), s.end(), std::ostream_iterator<std::string::value_type>( std::cout));
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats

This topic is closed to new replies.

Advertisement