Re: How to display individual character using string?
On Jun 9, 8:20 pm, Alan Woodland <aj...@aber.ac.uk> wrote:
Harald Finster wrote:
Immortal Nephi wrote:
// how to use loop to print each character individual between space?
[snip]> //
// suggestion2:
// better: using for_each
// use the 'print' method defined above is executed for each
// character of the string which can be regarded as a
// sequence of chars
//
for_each( s1.begin(),s1.end(),print);
cout << endl;
//
// suggestion3:
// like suggestion2 but
// more object oriented style:
// use a function object instead of the global function
// operator() of WhiteSpaceSeparatedPrinter is executed
// for each character in the string
WhiteSpaceSeparatedPrinter whiteSpaceSeparatedPrinter;
for_each( s1.begin(), s1.end(), whiteSpaceSeparatedPrinter );
cout << endl;
// you could probably also use a stream_iterator in combination
// with a function
Better still:
#include <string>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
int main()
{
string s1 = "The cat is cute.";
cout << s1 << endl;
copy(s1.begin(), s1.end(), ostream_iterator<char>(cout, " "));
return 0;
}
Which outputs an extra space at the end. (It would be nice if
there were a variant of ostream_iterator which generated
separators correctly, but there isn't.) One could add a test
and use the ostream_iterator for all but the last character,
something like:
if ( ! s1.empty() ) {
std::copy( s1.begin(),
s1.end() - 1,
std::ostream_iterator< char >( std::cout, " " ) ) ;
std::cout << *(s1.end() - 1) ;
}
But that still wouldn't meet the stated requirement: "use a loop
to print each character[...]". (Of course, such a requirement
clearly indicates homework.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34