|
-
March 29th, 2008, 03:48 PM
#1
using an iterator.
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.
Code:
#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);
}
-
March 29th, 2008, 04:09 PM
#2
Re: using an iterator.
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!
Code:
#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;
}
-
March 29th, 2008, 04:09 PM
#3
Re: using an iterator.
There are quite a few ways to do this, here's one:
Code:
std::copy(s.rbegin(), s.rend(), std::ostream_iterator<std::string::value_type> (std::cout));
-
March 29th, 2008, 05:09 PM
#4
Re: using an iterator.
 Originally Posted by Plasmator
There are quite a few ways to do this, here's one:
Code:
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.
-
March 29th, 2008, 05:13 PM
#5
Re: using an iterator.
 Originally Posted by ptg
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:
Code:
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.
-
March 29th, 2008, 05:24 PM
#6
Re: using an iterator.
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
Last edited by ptg; March 29th, 2008 at 06:47 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|