Harry Harry - 1 month ago 5
C Question

Printing a name in Standard format

I am trying to develop a basic program that takes your name and provides the output in standard format. The problem is that I want the user to have an option of not adding the middle name.

For Example: Carl Mia Austin gives me C. M. Austin but I want that even if the Input is Carl Austin it should give me C. Austin without asking the user if they have a middle name or not.
So, Is there a way or function which could automatically detect that??

#include <stdio.h>

int main(void) {
char first[32], middle[20], last[20];

printf("Enter full name: ");
scanf("%s %s %s", first, middle, last);
printf("Standard name: ");
printf("%c. %c. %s\n", first[0], middle[0], last);

return 0;
}

Answer

As currently written, scanf("%s %s %s", first, middle, last); expects 3 parts to be typed and will wait until the user types them.

You want to read a line of input with fgets() and scan that for name parts with sscanf and count how many parts were converted:

#include <stdio.h>

int main(void) {
    char first[32], middle[32], last[32];
    char line[32];

    printf("Enter full name: ");
    fflush(stdout);  // make sure prompt is output
    if (fgets(line, sizeof line, stdin)) {
        // split the line into parts.
        // all buffers have the same length, no need to protect the `%s` formats
        *first = *middle = *last = '\0';
        switch (sscanf(line, "%s %s %[^\n]", first, middle, last)) {
        case EOF: // empty line, unlikely but possible if stdin contains '\0'
        case 0:  // no name was input
            printf("No name\n");
            break;
        case 1:  // name has a single part, like Superman
            printf("Standard name: %s\n", first);
            strcpy(last, first);
            *first = '\0';
            break;
        case 2:  // name has 2 parts
            printf("Standard name: %c. %s\n", first[0], middle);
            strcpy(last, middle);
            *middle = '\0';
            break;
        case 3:  // name has 3 or more parts
            printf("Standard name: %c. %c. %s\n", first[0], middle[0], last);
            break;
        }
    }
    return 0;
}

Note that names can be a bit more versatile in real life: think of foreign names with multibyte characters, or even simply William Henry Gates III, also known as Bill Gates. The above code handles the latter, but not this one: Éléonore de Provence, the young wife of Henry III, King of England, 1223 - 1291.

Comments