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);
}
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 . . .
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.