Tyler
Tyler

Reputation: 21

How to use toupper library function in C?

I need to print the initials of a name, like tyler jae woodbury would print TJW, but I can't seem to print the uppercase initials.

This is my code:

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

string get_initials(string name, char initials[]);

int main(void)
{
    // User input
    string name = get_string("Name: ");

    // Gets the users initials
    char initials[10];
    get_initials(name, initials);
    printf("%s\n", initials);
}

string get_initials(string name, char initials[])
{
    int counter = 0;

    for (int i = 0, n = strlen(name); i < n; i++)
    {
        if (name[i] == ' ')
        {
            initials[counter] = name[i+1];
            counter++;
        }
        else if (i == 0)
        {
            initials[counter] = name[i];
            counter++;
        }
    }
    return initials;
}

I know that usually toupper() is used for chars, and the print statement declares a string, but I don't know what to do.

Upvotes: 2

Views: 229

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

The function is incorrect.

For starters in general a string can contain adjacent spaces between words or have trailing adjacent spaces.

Secondly the function does not build a string because it does not append the terminating zero character '\0' to the destination array.

Also the call of strlen is inefficient and redundant.

To convert a symbol to upper case use standard function toupper declared in the header <ctype.h>

Also the function declaration is confusing

string get_initials(string name, char initials[]);

Either use

string get_initials(string name, string initials);

or it will be better to write

char * get_initials( const char *name, char *initials);

The function can be defined the following way as shown in the demonstration program below.

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

char * get_initials( const char *name, char *initials )
{
    const char *blank = " \t";

    char *p = initials;

    while ( name += strspn( name, blank ), *name )
    {
        *p++ = toupper( ( unsigned char )*name );

        name += strcspn( name, blank );
    }

    *p = '\0'; 

    return initials;
}

int main( void ) 
{
    char name[] = " tyler jae woodbury ";
    char initials[10];

    puts( get_initials( name, initials ) );
}

The program output is

TJW

Upvotes: 1

Related Questions