I am having trouble understanding what getchar() != ' '
and getchar() = ' '
are doing in my code.
Why do there need to be opposites.
The user may input extra spaces between the first name and last, and before the first name and after the last name.
#include <stdio.h>
int main(void) {
char c, initial;
printf("Enter a first and last name: ");
scanf(" %c", &initial);
printf("%c\n", initial);
while ((c = getchar()) != ' ')
;
while ((c = getchar()) == ' ')
;
do {
putchar(c);
} while ((c = getchar()) != '\n' && c != ' ');
printf(", %c.\n", initial);
return 0;
}
In this code snippet
scanf(" %c", &initial);
// printf("%c\n", initial); <== remove this statement
while ((c = getchar()) != ' ')
;
The first letter of the first name is read and other letters are skipped.
This loop
while ((c = getchar()) == ' ')
;
skips spaces between the first name and the second name.
This loop
do {
putchar(c);
} while ((c = getchar()) != '\n' && c != ' ');
outputs all letters of the second name.
And at last the first letter of the first name is outputted after the full second name.
So if you entered for example
Nick Fisher
then the output should be
Fisher, N.
Take into account that you should remove the statement
printf("%c\n", initial);
it is a redundant statement.