I am writing code to enter a string and convert all its uppercase letters to lowercase and vice versa:
#include <iostream>
#include <string>
using namespace std;
int main(){
string s;
cout<<"enter the string :"<<endl;
cin>>s;
for (int i=0;i<s.length();i++){
if ('a'<=s[i] && s[i]<='z'){
s[i]=char(((int)s[i])-32);
}
if ('A'<=s[i] && s[i]<='Z'){
s[i]=char(((int)s[i])+32);
}
}
cout<<"modified string is : "<<s<<endl;
return 0;
}
Problem is that it always returns string with all lower case letters and none of them is upper case. Why?
You’re converting all lower case to upper case in the first if-statement. However, the same letters that were changed to uppercase will immediately be changed to lower case again in the second if-statement.
What you want is an
else if.