0

i have to output a string in all uppercase if count of uppercase characters in it is more otherwise lowercase string will be shown if lowercase characters are more in the string,in case both characters are equal i will print the string in lowercase only this the code i have written , but , it's not giving desired output,like it is returning the same string back to me , please help me with the errors

here's the code,i am using c++.

string s;
cin>>s;
int uc=0,lc=0;
for (int i = 0; i < s.size(); i++)
{       
    if(isupper(s[i])){
        uc++;
    }
    else{
        lc++;
    }
}
if(uc>lc){
    for (int j = 0; j < s.size(); j++)
    {
        toupper(s[j]);

    }    
    cout<<s<<endl;
}
else{
    for (int k = 0; k < s.size(); k++)
    {
        tolower(s[k]);
    }
    cout<<s<<endl;
}
  • 1
    The counting is very easy with [`std::count_if`](https://en.cppreference.com/w/cpp/algorithm/count). Then "converting" can easily be done with [`std::transform`](https://en.cppreference.com/w/cpp/algorithm/transform). – Some programmer dude Feb 10 '22 at 10:08
  • 2
    `toupper` and `tolower` return the modified character, so you have to store those back if you want to change the original. – BoP Feb 10 '22 at 10:09
  • 1
    By the way, in your current code, note that your logic for counting lower-case is flawed: It will count space, punctuation and digits as lower-case letters. – Some programmer dude Feb 10 '22 at 10:10

2 Answers2

1

Your problem is that your are not re-assigning the respective characters of your string resulting in your input string being untouched.

You need to do:

s[j] = toupper(s[j])
s[k] = tolower(s[k]);

Another approach is to convert the string as a whole after your counting procedure - requires to include <algorithm> (credits to this answer):

if (uc > lc) {
    std::transform(s.begin(), s.end(), s.begin(), ::toupper);
}
else {
    std::transform(s.begin(), s.end(), s.begin(), ::tolower);
}
Odysseus
  • 1,213
  • 4
  • 12
-2

After your first loop, do this:

string result = (uc>lc) ? toupper(s) : tolower(s);
Niels Holst
  • 586
  • 4
  • 9