Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: C++ strings in upper/lower case  (Read 23652 times)

0 Members and 1 Guest are viewing this topic.

Dilbert

    Topic Starter
  • Moderator


  • Egghead

  • Welcome to ComputerHope!
  • Thanked: 44
    C++ strings in upper/lower case
    « on: December 10, 2006, 11:27:59 PM »
    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:

    Code: [Select]
    //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
    « Last Edit: March 30, 2007, 02:55:08 AM by Dilbert »
    "The geek shall inherit the Earth."