Can't use convert upper to lower character

Viewed 62

If I execute this code

#include <iostream>

using namespace std;

int main()
{
    string word;
    getline(cin, word);
    
    for (char ch: word) {
   
        if (isupper(ch))
            ch=tolower(ch);
        
    }
    cout<<word<<endl;
    return 0;
}

The characters don't convert to lower cases... What could have gone wrong?

2 Answers

Consider this piece of code:

char a = 'x';
char b = a;
b = 'y';

What is the value of a at the end? It is 'x' because a and b are distinct objects, and modifying b has no effect on the value of a.

Same applies to your code. The loop variable:

for (char ch: word)
     ^^^^^^^

is a distinct object from the element of the string. Modifying that object has no effect on the string. In order to modify the string, you need to use indirection. Use a reference to char instead of a char:

for (char& ch: word)

The issue with your code snippet is that you modify the copy of each character instead of the characters within the string.

In other words, in your loop, you need to take a reference of each character:

for (char& ch: word) 

Here is a quick code snippet that does what you want to achieve:

#include <iostream>
#include <string>
#include <cassert>

static bool convert_str_to_lower(std::string* word) {
    if (word == nullptr) return false;
    
    for (char& ch : *word) {
        if (std::isupper(ch)) ch=std::tolower(ch);
    }
    return true; 
}    

int main() {
    std::string word = "FoOBaR";
    assert(convert_str_to_lower(&word));
    assert(word.compare("foobar") == 0);
    
    std::cout << "converted str: " << word << "\n";
    return 0; 
}
Related