Click to See Complete Forum and Search --> : using an iterator.
ptg
March 29th, 2008, 03:48 PM
i want to type in a word and for my program to output it backwards. but i have to use an iterator.
ex: "clue" and it should print it out "eulc"
this is what i have so far.
#include <iostream>
#include<string>
using namespace std;
int main(){
string s;
cout << "Enter a word: ";
getline( cin, s );
string::iterator r;
r = s.begin();
while ( r != s.end() ){
cout<< *r;
r++;
}
cout<<endl;
return (0);
}
HJK
March 29th, 2008, 04:09 PM
Hi, not the prettiest implementation ever, but it works - for more than just a single word also. take a look at it and fiddle with it!
#include <iostream>
#include<string>
using namespace std;
// get a whole line, char by char from cin
int getPhrase(string &buffer)
{
char buff;
while(buff != '\n')
{
cin.get(buff);
buffer += buff;
}
return buffer.length();
}
int main(){
// origional
string s;
// reversed
string reverse;
cout << "Enter a phrase: ";
int len = getPhrase(s);
for(int i=0;i<=len;i++)
{
// reverse the string
reverse += s[len-i];
}
cout << reverse << endl;
//(fanfare!)
return 0;
}
Plasmator
March 29th, 2008, 04:09 PM
There are quite a few ways to do this, here's one:
std::copy(s.rbegin(), s.rend(), std::ostream_iterator<std::string::value_type> (std::cout));
ptg
March 29th, 2008, 05:09 PM
There are quite a few ways to do this, here's one:
std::copy(s.rbegin(), s.rend(), std::ostream_iterator<std::string::value_type> (std::cout));
i dont quite understand what you meant by that im a beginner to c++
and HJK i need a way to make it print backward within the iterator.
Plasmator
March 29th, 2008, 05:13 PM
i dont quite understand what you meant by that im a beginner to c++Based on your original example, here's the for-loop equivalent:
for(std::string::const_reverse_iterator r = s.rbegin(), end = s.rend(); r != end; ++r)
{
std::cout << *r;
}
Provided that you don't need to reverse the contents of the string itself.
ptg
March 29th, 2008, 05:24 PM
oh is that im learning it in another way so your code seemed strange to me but i have seen it like that before. thanks for the help
okay i got it to work but it loops it too many times. i only want it to print once
never mind i figured it out
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.