Thread: My program is skipping my second getchar() input statement.

  1. #1
    Registered User
    Join Date
    Sep 2018
    Posts
    4

    My program is skipping my second getchar() input statement.

    Hi, I'm new to input and output in C. The following code has two input statements:
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    //SamsFirst_IO.c
    
    int main(){
        int x,y;
        printf("Type a letter: ");
        x = getchar();
        printf("Type another letter: ");
        y = getchar();
        //printf("You typed '%c'.\n",c);
        putchar('\n');
        printf("You typed ");
        putchar(x);
        printf(" and ");
        putchar(y);
        printf(".\n");
        
        return(0);
    }
    But the console ignores my second input statement and looks like this:
    My program is skipping my second getchar() input statement.-01-png
    What's going on?

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    You typed in a newline character.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,110
    Quote Originally Posted by UncleBazerko View Post
    Hi, I'm new to input and output in C.
    ...
    What's going on?
    When you type in 'x' and press enter, you are actually entering 2 characters. The first getchar() assigns 'x' to the variable, x. The Second getchar() then assigns the newline char to the variable y.

    You need to clean out the input buffer after the first getchar(). It is commonly done with the following statements:

    Code:
    int ch = 0;
    while ((ch = getchar()) != '\n' && ch != EOF);
    DO NOT try to use, "fflush(stdin)"!!! fflush() is for output files ONLY!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. cin statement skipping
    By joe6032 in forum C++ Programming
    Replies: 1
    Last Post: 10-06-2014, 10:35 PM
  2. Program skipping if statement
    By russiancircles in forum C++ Programming
    Replies: 0
    Last Post: 03-16-2014, 05:55 PM
  3. Program skipping input....Scanf()
    By steve5591 in forum C Programming
    Replies: 2
    Last Post: 11-17-2010, 06:53 PM
  4. Skipping if statement
    By FallenBlade in forum C Programming
    Replies: 6
    Last Post: 12-13-2009, 03:40 PM
  5. Program skipping some input
    By Dita in forum C++ Programming
    Replies: 3
    Last Post: 08-28-2004, 03:08 PM

Tags for this Thread