Question
I've got a program I'm writing in C++ and I need user input to be all lower or uppercase. How can I get this without spitting error messages every time someone capitalizes/doesn't capitalize a single letter?
Answer
This probably isn't a common question, but it's one that led me on a long chase with several answers that would mess up depending on the compiler. This is stupid. There is a method, quick and easy, that works in C++, and it should be kept within easy access, in my opinion, because anyone who is learning C++ will play with the getline(cin) stuff and will want to use conditional statements with that input. It's all part of learning. So, an example:
//To lowercase
string x = "DilBERt"; //So we get a mix.
for(int i = 0; i < 100; i++) //This makes sure that we get the whole word.
{
if(x[i] + 32 < 122) //122 is the value for "z".
{
x[i] += 32; //32 is the difference between an uppercase and its lower counterpart
}
}
For conversion to uppercase, change the if statement to
if(x - 32 > 65) // 65 is the value for "A".
and x += 32 should be changed to x -= 32