c++c-stringsfunction-definitiontoupper

Passing a pointer into methods in C++ resulting in weird output


I am trying to convert a string of characters to Upper case by passing a pointer into a toUpper method that I have created. The logic seems to be fine but I get a weird output like ìëïà. Any ideas where I have gone wrong here?

#include <iostream>
#include <string.h> 

using namespace std;

void toUpper(char *);

int main()
{
    char name[80];
    char *namePtr = name;

    cout << "Enter a name :";
    cin >> name;

    toUpper(namePtr);
    cout << "The string in Upper Case is: " << name << endl;


}

void toUpper(char *p)
{

    int asciiValue; 

    // Loop through each char in the string
    for(int i = 0 ; i < strlen(p); i++)
    {
        
        asciiValue = (int) p[i];

        if(asciiValue >= 97 && asciiValue <= 122)
        {
            asciiValue = asciiValue + 32;
            p[i] = asciiValue;
        }
    }

}




Solution

  • Your problem boils down to bad magic numbers, which makes it nearly impossible to tell even from a close look because they're magic numbers!

    Instead, I'd use character literals to make things obvious:

    if(asciiValue >= 'a' && asciiValue <= 'z')
    {
        asciiValue = asciiValue + ('a' - 'A');
        p[i] = asciiValue;
    }
    

    Now it should be pretty apparent that you're adding the wrong value! It should instead be:

    asciiValue = asciiValue + ('A' - 'a');