asunnysunday
asunnysunday

Reputation: 321

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

Upvotes: 2

Views: 3033

Answers (3)

Opera
Opera

Reputation: 983

Using getchar() to read a string from the standard input is not really efficient. You should use read() or scanf() to read the input into a buffer an then work on your string. It will be much easier.

Anyway, I added a comment where you bug is.

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

// Your bug is here : you don't use the character which got you out of your first loop.

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

Upvotes: 0

Adam
Adam

Reputation: 17329

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.

Upvotes: 3

Mat
Mat

Reputation: 206679

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

This part is wrong. The if in there will never match, because that block is only run if ch == ' '.

while ((ch = getchar()) == ' ');
printf("%c", ch);  //print the first letter of the last name

should fix it.

Note that getchar returns an int, not a char. If you want to check for end of file at some point, this will byte you if you save getchar's return value in a char.

Upvotes: 2

Related Questions