Unable to convert values from lowercase to uppercase using toupper

1.3k views Asked by At

i'm attempting to create a program that asks the user to firstly enter the amount of values they would like to convert from lowercase to uppercase. The for loop then assigns each value into an array. The array then goes through another for loop to convert the values into uppercase using LowerToUpper function.

When i go to run the program, it will take in values and then start doubling them on the command window, and will cease when you have completed entering the values, rather than printf the results. Could you please explain why. Thank you in advance

#include<stdio.h>
#include <string.h>
#include <ctype.h>

void LowerToUpper(char* array)
{

        toupper(*array);
}

int main(void)
{
        int i, amount;
        printf("How many values?\n");
        scanf("%d", &amount);
        char *d;
        char array1 [amount];

        printf("Please enter the values\n");

        for(i=0; i<amount; i++)
        {
                scanf("%c", &array1[i]);
        }


        for(i=0; i<amount; i++)
        {
                d=&array1[i];
                LowerToUpper(d);
                scanf("%c", &array1[i]);
                printf("%c", array1[i]);
        }

        return 0;
}
2

There are 2 answers

1
Sourav Ghosh On

You are not using toupper() properly. The function returns the converted value in case of success. You need to make use of the returned value. The supplied argument is not changed.

That said, the program structure is unnecessarily complicated. you can simplify it like

    for(i=0; i<amount; i++)
    {
            int result = toupper (array1[i]);
            if (result != array1[i]) printf("%c", result); //just checkin', if converted
    }

That said, you have many other issue which you don't see at this moment, like

    scanf("%c", &array1[i]);

this will, to your surprise, only ask you for half the number of inputs. Why? You forgot to ignore the newline entered by RETURN key.

Then, you did not check for the success of scanf("%d", &amount); call. In case, the scanning fails, you'll end up with undefined behavior.

The second scanf() inside the last for loop is probably something you don;t want, it's useless, at best.

5
gsamaras On

Change this:

toupper(*array);

to this:

*array = toupper(*array);

since toupper ref's mentions:

Return Value

The uppercase equivalent to c (*array in your case), if such value exists, or c (unchanged) otherwise. The value is returned as an int value that can be implicitly casted to char.


PS: Defining a function LowerToUpper() for this operation (one line of code) is an overkill, and you could call that one line of code inside main() instead (I mean the body of the function to be moved into main()).