Click to See Complete Forum and Search --> : Problem in C++ ( cout )


Concrete Geist
01-30-2002, 08:32 PM
Ok, this program must reverse a string and output it. The problem is not reversing the string, but rather outputting it. I must use string class, and when I try to output the string with cout, nothing happens. here is the code :


#include <iostream.h>
#include <string>

inline int strlen( const string& );

int main(void)
{
string name, reversename;
int index;

cin >> name;

for( index=0; index < strlen(name); index++ )
{
reversename[index] = name[strlen(name)-index-1];
cout << reversename[index];
} cout << endl;

return 0;
}

inline int strlen( const string& s )
{
int index;
for( index = 0; s[index] != '\0'; index++ )
; /* Nothing */
return index;
}


This program uses a for loop to output the string and that works well, but I can't use a loop. :(

sans-hubris
01-30-2002, 09:40 PM
A few things. The string class has a length() member function. When using the string class (or STL containers), always use the at() member function instead of the index ([]) operators to avoid address memory outside the string or container.

Finally, to avoid using a loop, check out the STL reverse and reverse_copy algorithms. http://www.dinkumware.com/htm_cpl/algorith.html#reverse

tecknophreak
01-30-2002, 11:01 PM
i didn't even think strlen(string) would even compile?? :rolleyes:

did you get that to compile? and with what compiler? gnu gcc?

Concrete Geist
01-30-2002, 11:19 PM
Yes this whole thing compiles on GCC. What would be wrong with it?

[ 30 January 2002: Message edited by: Concrete Geist ]

tecknophreak
01-30-2002, 11:34 PM
uhh...nevermind. i just glanced over the code without even looking for more then a second. i thought it was the old strlen(const char*) strlen. :rolleyes:

my bad. ok, i withdraw that comment, sorry about any confusion.