Reverse Function (String)

This is my first semester of C++ programming. I need this function to output a whole string mirrored. Even with spaces like "This is a sentence". When I run it, it only reverses the first word. For example, "Aaron = noraA". Thank you.

#include <iostream>

using namespace std;

string sReverse(string s)
{
string r = "";
int i =s.length() -1;
while (i >= 0)
{
r += s[i];
i--;
}
return r;
}

int main ()
{
string s, r;

cout << "Enter a string: ";

cin >> s;

r = sReverse(s);

cout << sReverse(s);
}
Change
cin >> s;
to
getline( cin, s );
This is formatted input:
1
2
string s;
cin >> s;

See: http://www.cplusplus.com/reference/string/string/operator%3E%3E/
Notice that the istream extraction operations use whitespaces as separators; Therefore, this operation will only extract what can be considered a word from the stream. To extract entire lines of text, see the string overload of global function getline.

http://www.cplusplus.com/reference/string/string/getline/
Last edited on
Thank you!
Topic archived. No new replies allowed.