Search code examples
cgetchar

Problem with getchar in C


I want to write a program which can: when I enter, say "Alan Turing", it outputs "Turing, A". But for my following program, it outputs "uring, A", I thought for long but failed to figure out where T goes. Here is the code:

#include <stdio.h>
int main(void)
{
char initial, ch;

//This program allows extra spaces before the first name and between first name and second name, and after the second name.

printf("enter name: ");

while((initial = getchar()) == ' ')
    ;

while((ch = getchar()) != ' ')  //skip first name
    ;

while ((ch = getchar()) == ' ')
{
    if (ch != ' ')
        printf("%c", ch);  //print the first letter of the last name
}
while((ch = getchar()) != ' ' && ch != '\n')
{
    printf("%c", ch);
}
printf(", %c.\n", initial);

return 0;
}

Solution

  • Your bug is here:

    while ((ch = getchar()) == ' ')
    {
        if (ch != ' ')
            printf("%c", ch);  //print the first letter of the last name
    }
    while((ch = getchar()) != ' ' && ch != '\n')
    {
        printf("%c", ch);
    }
    

    The first loop reads characters until it finds a non-space. That's your 'T'. Then the second loop overwrites it with the next character, 'u', and prints it. If you switch the second loop to a do {} while(); it should work.