Deadlines_BR Deadlines_BR - 1 month ago 9
C Question

CS50 (pset2) - Behavior not understood in C program that prints out initials

I have prior experience with Python but absolute beginner in C. I am working on CS50x pset2 initials (less comfortable), where a simple C program is supposed to accept a name given by the user and the print out its initials of the name.

When I run the program, it seems to work for some situations, but for some names it is appending a wrong 'B' char at the end. Here is the code:

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

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

int main(void)
{
// user input (full name)
printf("Please type your name: ");
string name = get_string();

// get the user name initials
char initials[10];
get_initials(name, initials); // in: full name; out: initials
printf("Initials: %s\n", initials);

}

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

// Iterate over all characters
for (int i = 0, n = strlen(name); i < n; i++)
{
// in case the i-th char is ' ', appends next char to the initials array
if (name[i] == ' ')
{
initials[counter] = name[i+1];
counter++;
}
// appends the first char to the initials array
else if (i == 0)
{
initials[counter] = name[i];
counter++;
}
}
return initials;
}


And here are some Terminal outputs:

~/workspace/pset2/ $ ./initials
Please type your name: John Smith
Initials: JSB
~/workspace/pset2/ $ ./initials
Please type your name: John Smith Here
Initials: JSH
~/workspace/pset2/ $ ./initials
Please type your name: John
Initials: J
~/workspace/pset2/ $ ./initials
Please type your name: John Smith Here Again
Initials: JSHAB
~/workspace/pset2/ $ ./initials
Please type your name: John Smith Here Again Where
Initials: JSHAW
~/workspace/pset2/ $ ./initials
Please type your name: John Smith Here Again Where Here
Initials: JSHAWH
~/workspace/pset2/ $


I debugged for "John Smith" but still can't understand why it is appending S\320\330B instead of just S.

Answer Source

At the end of the get_initials function, terminate the string:

...
initials[counter] = '\0';
return initials;