DKXP
DKXP

Reputation: 61

CS50 Week 2 Substitution: Converting a string to uppercase

I'm trying to convert a string to all uppercase using below:

string key = argv[1];

    for (int i = 0; i < len; i++)
    {
        if islower(key[i])
        {
            toupper(key[i]);
        }
    }

I'm receiving:

substitution.c:59:13: error: ignoring return value of function declared with pure attribute [-Werror,-Wunused-value]
            toupper(key[i]);

Could anyone help me understand what this means?

The other part of the code is listed below if that's relevant.

int main(int argc, string argv[])
{
    // strlen = 26
    int len = strlen(argv[1]);
    if (len != 26)
    {
        printf("Usage: ./substitution key\n");
        return 1;
    }
    // input must be single string
    if (argc != 2)
    {
        printf("Usage: ./substitution key\n");
        return 1;
    }
    // check each char as letter
    for (int i = 0; i < len; i++)
    {
        if (!isalpha(argv[1][i]))
        {
        printf("Usage: ./substitution key\n");
        return 1;
        }
    }
    // check for duplicates
    for (int i = 0; i < len; i++)
    {
        for (int j = i + 1; j < len; j++)
        {
            if (toupper((argv[1][i])) == toupper((argv[1][j])))
            {
                printf("Usage: ./substitution key\n");
                return 1;
            }
        }
    }

Thanks!

Trying to convert a string to all uppercase but ran into an error that I can't understand. Thanks!

Upvotes: 1

Views: 171

Answers (1)

Madagascar
Madagascar

Reputation: 7345

From the man page:

DESCRIPTION:

These functions convert lowercase letters to uppercase, and vice versa.

If c is a lowercase letter, toupper() returns its uppercase equivalent, if an uppercase representation exists in the current locale. Otherwise, it returns c. The toupper_l() function performs the same task, but uses the locale referred to by the locale handle locale.

If c is an uppercase letter, tolower() returns its lowercase equivalent, if a lowercase representation exists in the current locale. Otherwise, it returns c. The tolower_l() function performs the same task, but uses the locale referred to by the locale handle locale.

OP's Problem:

toupper(key[i])

does not change the supplied argument. It returns the uppercase equivalent of the character, if available. You need to make use of it.

Change this:

toupper(key[i);

to:

key[i] = toupper(key[i]);

You're also missing a pair of parentheses around the if statement.

Upvotes: 1

Related Questions