Reverse String

I initially posted this in the beginners forum, maybe too much to ask there, I have the string to change toupper and tolower but I cannot get the original string to do the revers of the case of the initial string, I know I need something added, and I know that my code works besides the fact that it is not changing the initial string but it change whatever the string was last changed to.

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

void convert(string& s)
{
for (int i = 0; i < s.length(); i++)
{
s[i] = toupper(s[i]);
}
}

void convert1(string& s)
{
for (int i = 0; i < s.length(); i++)
{
s[i] = tolower(s[i]);
}
}

void convert2(string& s)
{
for (int i = 0; i<s.length(); i++) {
if ('a' <= s[i] && s[i] <= 'z') {
s[i] = char(((int)s[i]) - 32);
}

else if ('A' <= s[i] && s[i] <= 'Z') {
s[i] = char(((int)s[i]) + 32);
}
}


}


int main()
{
{
string s;
cout << "Enter a string" << endl;
getline(cin, s);

cout << "Here is the string in all upper case" << endl;
convert(s);
cout << s << endl;

cout << "Here is the string in all lower case" << endl;
convert1(s);
cout << s << endl;

cout << "Here is the string reversed" << endl;
convert2(s);
cout << s << endl;


}

return 0;
}
Here is the output I am getting right now

Enter a string
Hello World
Here is the string in all upper case
HELLO WORLD
Here is the string in all lower case
hello world
Here is the string reversed
HELLO WORLD
Press any key to continue . . .

I need the last output to be hELLO wORLD
Just store the original string in another variable and pass that to convert2()
Don't pass by reference!
I did try storing the original string however the the result kept coming up the original string and would not convert it.
Inverting the case from "Hello World" to "hELLO wORLD" is reversible. Do the same operation again and the original string is restored.

On the other hand, converting to all upper case or all lower case is not reversible, some information is lost in the process. Therefore you have to store a copy if you want access to the original text after calling either of those.

Or rearrange the code a little. Instead of this:
1
2
3
    cout << "Here is the string in all upper case" << endl;
    convert(s);
    cout << s << endl;
put this:
 
cout << "Here is the string in all upper case\n" << convert(s) << endl;


... and change the function so that it returns a string, instead of being declared as void. It should of course not modify the parameter in this case, so pass it by value (or perhaps constant reference):
1
2
3
string convert(string s)
{
    // etc. 


One more thing. Please consider choosing meaningful names for your functions so it isn't necessary to read the code to discover what they do.
Last edited on
Tried your changed, get the same results
Needs context. It's not possible to say why the result is not as required without seeing the latest version of the code.
Last edited on
Topic archived. No new replies allowed.