Search code examples
cvisual-studio-2012getchar

getchar() skips every other char in C


I have been having problems fully using getchar() for a while now in C. And in this case I am trying to read a line and put the char's of the line into an array. However upon assigning the getchar() to the array it skips some characters.

For example the input "It skips every other" the output is...I\n \n k\n p\n \n v\n r\n \n t\n e\n. (the \n is just to represent the new line.)

int N = 0;

char message[80] = {};

do
{
    message[N] = getchar();
    N++;
    printf("%c\n", message[N-1]);
}
while(getchar() != '\n');

Thank you for your time, as stated before almost anytime I have ever tried to use getchar() it always gives some unexpected result. I don't fully understand how the function reads the char's.


Solution

  • You're calling getchar() twice one in the while condition and other inside the do-while body.

    Try this code instead:

    int N = 0;
    #define MAX_SIZE 80
    
    char message[MAX_SIZE] = {};
    char lastChar;
    
    do
    {
        lastChar = getchar();  
        if (lastChar == '\n')
            break; 
        message[N] = lastChar;
        N++;
        printf("%c\n", message[N-1]);
    }
    while(N < MAX_SIZE);
    

    UPDATE: Added checks for maximum size of the array instead of using an infinite do-while loop.