0

I need to use a character array and take the characters in the array and capitalize and lower case them as necessary. I was looking at the toupper and its example, but I'm confused about how this works. Looking from the example given on cplusplus.com I wrote

int main(){
    int i = 0;
    char str[] = "This is a test.";
    while(str[i]){
        putchar(toupper(str[i]));
        i++;
    }
    for(int i = 0; i < 15; i++){
        cout << str[i];
    }
}

and there are two things I don't understand about this. The first is that without the cout at the bottom, the program prints out THIS IS A TEST. Does putchar print to the screen? (the use of putchar is not explained on the example). But my second more important question is why does the cout at the bottom still print out This is a test.? Does it not change the chars in str[]? Is there another way I should be doing this (keeping in mind I need to use character arrays)?

Tommy K
  • 1,759
  • 3
  • 28
  • 51
  • possible duplicate of [Convert a String In C++ To Upper Case](http://stackoverflow.com/questions/735204/convert-a-string-in-c-to-upper-case) – Samer Oct 17 '14 at 20:33
  • 1
    To actually change the contents of `str`, you could do `str[i] = toupper(str[i]);` in your loop. – iwolf Oct 17 '14 at 20:35
  • @iwolf I figured this out myself a minute before I saw your answer. I wish you put this as a answer so I could credit you. Thanks! – Tommy K Oct 17 '14 at 20:41
  • There are persistent rumours around the internets that you can enter things like "putchar" into a "search engine" device in order to locate documentation or examples. I'm not sure if those rumours are true, though. – molbdnilo Oct 17 '14 at 21:16

2 Answers2

2

Yes, putchar() prints a character to the program's standard output. That is its purpose. It is the source of the uppercase output.

The cout at the bottom of the program prints the original string because you never modified it. The toupper() function doesn't -- indeed can't -- modify its argument. Instead, it returns the uppercased char.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
1

putchar writes a single character to output: http://www.cplusplus.com/reference/cstdio/putchar/

As a result, the first while loop converts each character from str one at a time to upper case and outputs them. HOWEVER, it does not change the contents of str - this explains the lower case output from the second loop.

Edit:

I've expanded the first loop:

// Loop until we've reached the end of the string 'str'
while(str[i]){
    // Convert str[i] to upper case, but then store that elsewhere. Do not modify str[i].
    char upperChar = toupper(str[i]);
    // Output our new character to the screen
    putchar(upperChar);
    i++;
}
Malcolm Crum
  • 4,345
  • 4
  • 30
  • 49