Nick
Nick

Reputation: 25

getchar() != ' ' and getchar() = ' '

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;
}

Upvotes: 1

Views: 233

Answers (3)

derAnder0815
derAnder0815

Reputation: 1

isn't there a problem using a char for initial and then writing a lot of characters into it? I think your using not allocated memory for the name.
And the first printf("%c\n", initial); should generate an output of the first character entered.

Soooo...
Input:
Nick Fisher

Output:
N
Fisher, N.

or:

Fisher, N.
or:
program crash because of forbidden memory access

regards André

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

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.

Upvotes: 2

user3629249
user3629249

Reputation: 16540

regarding:

while ((c = getchar()) != ' ')
    ;

while ((c = getchar()) == ' ')
    ;

the first while() loop consumes the rest of the first name

the second while() loop consumes the spaces between the first and last name.

Upvotes: 0

Related Questions