std::tolower ignores return value, is there a way to fix this?

Dec 22, 2020 at 1:08pm
Hello, I just made a function that will turn your string into a lowercase letter but every time I run it doesn't work. The compiler says "tolower ignored return value". Is there a way to fix this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <locale>

std::string to_lower(const std::string& word) {
    std::locale loc;

    for(std::string::size_type i = 0; i <= word.length(); i++) {
        std::tolower(word[i], loc);
    }

    return word;
}


int main()
{
    std::cout << to_lower("Arthur Morgan");

    return 0;
}
Last edited on Dec 22, 2020 at 1:08pm
Dec 22, 2020 at 1:18pm
Use the char returned by std::tolower

word[i] = std::tolower( word[i], loc );
Dec 22, 2020 at 1:23pm
Thanks, it worked. I just removed the constant value because it can't change. But still, big thanks.
Dec 22, 2020 at 1:58pm
> I just removed the constant value because it can't change.

We can keep it const and return a result string that holds the lower case characters.

Something like this:

1
2
3
4
5
6
7
8
std::string to_lower( const std::string& word ) {

    std::locale loc;

    std::string result;
    for( char c : word ) result += std::tolower( c, loc );
    return result;
}

Dec 23, 2020 at 10:59am
Consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
std::string to_lower(std::string word)
{
	for (char& c : word)
		c = (char)std::tolower(c);

	return word;
}

void to_lower(std::string& word)
{
	for (char& c : word)
		c = (char)std::tolower(c);
}

Dec 23, 2020 at 11:31am
1
2
> for (char& c : word)
>		c = (char)std::tolower(c);


This may engender undefined behaviour.
Like all other functions from <cctype>, the behavior of std::tolower is undefined if the argument's value is neither representable as unsigned char nor equal to EOF. To use these functions safely with plain chars (or signed chars), the argument should first be converted to unsigned char
https://en.cppreference.com/w/cpp/string/byte/tolower#Notes


Note that the function that yvez used (std::tolower in <locale>) does not have this particular problem.
Topic archived. No new replies allowed.