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.
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
strlenis inefficient and redundant.To convert a symbol to upper case use standard function
toupperdeclared in the header<ctype.h>Also the function declaration is confusing
Either use
or it will be better to write
The function can be defined the following way as shown in the demonstration program below.
The program output is