i wrote a following program to convert alphabets in string with length 100
this way
lowercase alphabets should convert to uppercase alphabets and reverse
i expect this output for this input ADs.....>adS
but my output is a very strange thing!
Line 14: 65-90 are upper case characters. You want to add 32 (not subtract) to make the equivalent lower case character (97-122).
Line 16: Your else condition is everything that is not upper case. You want to explicitly test if a character is upper case (97-122) before subtracting 32 (not adding).
Since you are using C++ std:string, why not use the std::transform() function in <algorithm> and toupper()/tolower() functions? There is no need to muck around with C-style strings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::cout << "Please enter a string for case-conversion:\n";
std::cout << "> ";
std::string strInput;
std::getline(std::cin, strInput);
std::cout << '\n';
transform(strInput.begin(), strInput.end(), strInput.begin(), toupper);
std::cout << "The string converted to upper case is:\n" << strInput << "\n\n";
transform(strInput.begin(), strInput.end(), strInput.begin(), tolower);
std::cout << "The string converted to lower case is:\n" << strInput << "\n\n";
}
Please enter a string for case-conversion:
> ConverT thIS StrINg!
The string converted to upper case is:
CONVERT THIS STRING!
The string converted to lower case is:
convert this string!
#include <iostream>
#include <string>
int main()
{
std::cout << "Please enter a string for case-conversion:\n";
std::cout << "> ";
std::string strInput;
std::getline(std::cin, strInput);
std::cout << '\n';
std::cout << "String before conversion:\n" << strInput << "\n\n";
// walk through the string so each element can be modified
for (auto& sElement : strInput)
{
if (sElement != toupper(sElement))
{
sElement = toupper(sElement);
}
else
{
sElement = tolower(sElement);
}
}
std::cout << "String after conversion:\n" << strInput << '\n';
}
Please enter a string for case-conversion:
> ConverT thIS StrINg!
String before conversion:
ConverT thIS StrINg!
String after conversion:
cONVERt THis sTRinG!
The STL <string> library is so much easier to use than C-style strings.
#include<iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
int
main()
{
string str;
while (getline(cin, str)) {
for (auto &ch : str) {
if (isupper(ch)) {
ch = tolower(ch);
} elseif (islower(ch)) {
ch = toupper(ch);
}
}
cout << str << '\n';
}
}
If you want to do it yourself then here's one way. Note that I'm comparing the character to 'A', 'Z', 'a' and 'z' instead of hard-to-understand constants. Also to convert from, say upper case to lower, I've used ch -'A' + 'a'. ch-'A' will convert 'A' to 'Z' into numerical values 0 to 25. Adding 'a' to that will convert to 'a' to 'z'.