0

I've managed to whip up a solution in Python 3 that seems to work.

name = input("")

initials = name[0]

for i in range(0, len(name)):
    if (name[i].isspace()):
        initials += name[i + 1]

print(initials.upper())

However, I'm having trouble translating the syntax from Python 3 to C.

#include <cs50.h> #include <stdio.h> #include <string.h>
int main(void) { string name = get_string(); char initials = name[0]; // What data type should I use for this? for (int i = 0, len = strlen(name); i < len; i++) { if (name[i] == '\0') { initials = initials + name[i + 1]; // Python 3 by default // takes a string to be a // char array that can be appended } }
printf("%c\n", initials); }

Python 3 takes string as a character array that can be easily appended to. How can I go about doing the same with C?

1
  • Inside your if (name[i]… is the only place you do any work, but you're only entering that section if name[i] == '\0' which means you reached a null character, the end of string – Andrew Siplas Dec 2 '17 at 19:17
0

Single Character vs Array of Characters

In your function, you define initials as a single character and make that single character equal to whatever the first member of name is (e.g. first initial):

char initials = name[0];

This leaves room for only one initial!

see declaring char array vs malloc for two ways you might declare an array of characters instead.


String Concatenation

Unlike python and others where memory is allocated automatically, in C we need to figure out where we store all of the characters in a string. Per declaring char array vs malloc you have a couple of ways to allocate a character array:

  • char initals[4] (for instance) means you can store up to 3 characters on the stack—need 1 for space the '\0' null terminator which indicates “end-of-string”. You can create other variables and concatenate into them, but not “resize” this statically declared array to add space under this same name as far as I know.
  • char* initials =malloc(4); will allocate the same 4 which you can manage and realloc as needed as you will need the space prior to using strncat()

You can use strncat to append to an array of characters but you must make enough space—mind their manual pages

the size of dest must be at least strlen(dest) + n + 1.

strncat manual page

and make sure to free any memory that you malloc or realloc

You must log in to answer this question.