tolower() not working

If I input "2 Bad Dogs", the correct output should be "2baddogs", but instead, I get "2BadDogs". Any suggestions?
Last edited on
If you want to make all uppercase letters lowercase, you can look first to the ASCII table. Uppercase letters come first, so you can write if (str[i] < 'a'). The difference between uppercase and lowercase (A and a, Z and z, etc.) is 32. For example F + 32 = f, or K + 32 = k. Put this in the if statement:
1
2
3
if (str[i] < 'a'){
    str[i] += 32;
}


This should work, probably.
Hmm unfortunately, this does not solve the problem. Thank you for answering though.
The problem is that after calling erase the index i does not point to where it originally would have so you are skipping the characters after the spaces.

1
2
3
4
if(!isalpha(str[i]) && !isdigit(str[i])){
	        str.erase(i, 1);
	        --i;
	    }
"If I input "2 Bad Dogs", the correct output should be "2baddogs", but instead, I get "2BadDogs". Any suggestions?"

Simple. Use an If statement to test each character for uppercase by using the isupper() function. If the function returns true, change that character into lowercase using the tolower() function.

Ex.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

int main()
{
    string str = "UK MARINE";
    for (int i = 0; i < str.size(); ++i)
    {
        if (isupper(str[i]))
        {
            str[i] = tolower(str[i]);
        }
    }
    cout << str << endl;
    return 0;
}


Output: uk marine

EDIT: Oh by the way, if you want to eliminate the spacing in between, test for isspace().
Last edited on
Thanks guys :)
Topic archived. No new replies allowed.