C Primer Plus – Chapter 4 – Task 6 (string output)


Write a Program that requests the user’s first name and then the user’s last name. Have it print the entered names on one line and the number of letters in each name on the following line. Align each letter count with the end of the corresponding name, as in the following:

Klaus Dieter     5      6 

My Try

#include <stdio.h> #include <string.h>  void printWhitespace(int times) {     for (int i = 0; i < times; i++) {         printf(" ");     } }  int main(void) {     // get names     printf("first name: ");     char firstName[20];     scanf("%s", &firstName);     printf("last name: ");     char lastName[20];     scanf("%s", &lastName);      // display names     printf("%s %s\n", firstName, lastName);      // display number of characters under last character of names     int numOfWhitespace = strlen(firstName) - 1;     printWhitespace(numOfWhitespace);     printf("%d ", strlen(firstName));      numOfWhitespace = strlen(lastName) - 1;     printWhitespace(numOfWhitespace);     printf("%d\n", strlen(lastName)); } 

Does the author expect that from me? Or is there a better way to write that?