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

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
Use the char returned by std::tolower

word[i] = std::tolower( word[i], loc );
Thanks, it worked. I just removed the constant value because it can't change. But still, big thanks.
> 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;
}

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);
}

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.