Edward Rios Edward Rios - 2 months ago 14
C++ Question

c++ c-string topper function sometimes outputs random numbers in the end

I need to use a character array pointing to a function. In the function, I need it to make the input into all capital letters. I figured I'd use the toupper function, which worked great for certain input, but when I input certain words I end up getting weird symbols/numbers in the end of my output(see output). Any help?

Code



#include <iostream>
#include <cstring>
#include <string>

using namespace std;

void allUppercase(char*);

const int SIZE = 50;

int main()
{
char words[SIZE];

cout << "Please enter your text : ";
cin.get(words, (SIZE-1));

cout << "The keyboard input was \"" << words << "\".\n";
cout << "\nThe uppercase output is \"";
allUppercase(words);
cout << "\".\n";

return 0;
}

// outputs the string entered in uppercase letters
// (Use a character array to store the string)
void allUppercase(char *ch)
{
char temp[SIZE];

for (int i=0; i < SIZE; i++)
{
if (ch[i] != '\0')
temp[i] = toupper(ch[i]);
else
break;
}
cout << temp;
}


Example Output



output

Answer

You forgot to null terminate temp.

void allUppercase(char *ch) {
    char temp[SIZE];

    for (int i=0; i < SIZE; i++) {
        if (ch[i] != '\0') {
            temp[i] = toupper(ch[i]);
        } else {
            temp[i] = '\0';
            break;
        }
    }
    cout << temp;
}