Trying to understand toupper()

I'm reading through a beginning C++ book and am currently learning about loops. I am working on making a loop so that after the program has run, it asks if the user wants to run it again. I understand how the loops work, but I'm having trouble understanding this line of code that converts the answer to all caps in order to get around case sensitivity.

The program asks the user if they want to run the program again and stores the answer as a string called restart. Then this section of code converts it to all uppercase so yes/Yes/yEs/etc are all understood:

1
2
3
for (int i = 0; i < restart.length(); i++) {
   restart[i] = toupper(restart[i]);
}


I understand what the line of code is doing, but I don't understand how it's doing it. Could someone please explain to me what is happening in this 'for loop'?

Thanks!
As I guess restart variable is a std::string object(or maybe similar).
So std::string has method length, that returns quantity of symbols in the string.
so example
1
2
3
std::string name = "Denis";
size_t count = name.length(); //size_t it's unsigned int type usually
std::cout << count;

In this example output should be

5

Because variable name has 5 symbols('D', 'e', 'n', 'i', 's').

So I hope it's clear.

The next moment is the loop for

Returning to my example I can do
1
2
3
4
5
std::string name = "Denis";
for (size_t i = 0; i < name.length(); i++)
{
    std::cout << name[i] << '\n';
}

The output should be
1
2
3
4
5
D
e
n
i
s


I hope it clear that using [] with string we get one symbol(for std::string it has char type)

The function toupper converts given symbol to the same symbol but with cap representing so
 
std::cout << toupper('e');

output should be

E


And in the body of loop you do the following
1. you get a symbol from string 'restart' using operator[]
 
char ch = restart[i];

2. you call function toupper with got symbol and got new symbol that the same but it's capital latter
 
char capitalRepresentin = toupper(ch);

3. You say that symbol of restart variable with index[i] should be equal to this new symbol
 
restart[i] = capitalRepresentin;

After that you repeat the same actions in the loop while index i lesser then quantity symbols in the string.

According to my remarks you loop now looks like:
1
2
3
4
5
6
7
size_t count = restart.length();
for(size_t i = 0; i < count; ++i)
{
    char symbolFromString = restart[i];
    char capitalRepresenting = toupper(symbolFromString);
    restart[i] = capitalRepresenting
}


This code does the same thing but I think for beginner programmer it's more clearer.
Last edited on
Thanks for the explanation Denis! It's much clearer now.
Topic archived. No new replies allowed.