Converting Input to Uppercase?

Jul 16, 2014 at 7:03pm
closed account (j1CpDjzh)
I'm trying to create a sort of text-adventure game, but rather than having to check for the input being uppercase or lowercase, I'd rather convert it before checking it in an if statement.

I've created a function, and I know it works because when I print the output, it shows up capitalized, however when I check it with an if statement, it doesn't pass.

Here is my code:

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

using namespace std;

void stringUppercase(string x)
{
    int i;
    for (i = 0; i < x.length(); i++)
    {
        x[i] = toupper(x[i]);
    }
}

int main()
{
    string input;
    getline(cin, input);
    stringUppercase(input);
    //Check if the letter 'b' gets capitalized...
    if (input == "B")
    {
        cout << "Yay!";
    }
}


I've tried Googling the solution, but no luck.
Thank you so much in advanced for your answers!

P/S: I'm programming with a Mac, if that helps.
Jul 16, 2014 at 7:07pm
you want to pass it by reference. just simply change line 5 to void stringUppercase(string &x) read more on references here(middleish): http://www.cplusplus.com/doc/tutorial/functions/
Jul 16, 2014 at 8:39pm
You could also just do:

std::transform(input.begin(), input.end(), input.begin(), std::toupper)

which will convert the whole string to uppercase, all in one nice line :) This also introduces you to the <algorithm> header, which is incredibly useful.
Last edited on Jul 16, 2014 at 8:39pm
Jul 16, 2014 at 9:34pm
closed account (j1CpDjzh)
Thank you giblit and ResidentBiscuit so much!
Jul 17, 2014 at 11:15pm
toupper will return the uppercase equivalent of its argument.
tolower will do the same but with the lowercase equivalent.

This is out of my textbook on character conversions, hope it helps:

Each function simply returns its argument if the conversion cannot be
made or is unnecessary. For example, if the argument to toupper is not a lowercase letter, then toupper simply returns its argument unchanged. The prototypes of these functions are

int toupper(int ch);
int tolower(int ch);

The fact that these functions return an integer means that a statement such as

cout << toupper('a'); // prints 65

will print the integer that is the ASCII code of 'A' rather than printing the character 'A' itself. To get it to print the character, you can cast the return value to a char, as in

cout << static_cast<char>(toupper('a')); // prints A

or you can assign the return value to a character variable first and then print the character:

char ch = toupper('a');
cout << ch; // prints A
Last edited on Jul 17, 2014 at 11:16pm
Topic archived. No new replies allowed.