Thread: Program skipping input....Scanf()

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    1

    Question Program skipping input....Scanf()

    Code:
    
    #include <stdio.h>
    int _1st, end;
    char letter;
    
    
    int main(void)
    
    {
    
    
    
    scanf("%d", &_1st);
    scanf("%d", &end);
    
    
    scanf("%c", &letter);
    
    printf("_1st = %d\n", _1st);
    printf("Letter = %c\n", letter);
    printf("_2nd = %d\n", end);
    
    printf("\n\n");
    
    system("pause");
    
    
    }

    The code above has been causing me a lot of trouble. ANY help would be appreciated.
    I am new to C programming, as the code above may indicate, and I want to collect two numbers (the first two scanf()s) and then a letter (the third scanf() ). However, it seems as if the program completely skips the letter step and advances to displaying what was entered, not even giving a chance to enter the letter. What is going on? Is it my compiler or just me?


    THE OUTPUT FOR 8 and 20, for example:


    8 20
    _1st = 8
    Letter =

    _2nd = 20

  2. #2
    Just a pushpin. bernt's Avatar
    Join Date
    May 2009
    Posts
    426
    8 20
    _1st = 8
    Letter =

    _2nd = 20
    scanf leaves a newline in the input, which is being picked up when you read in a character, and this is being printed out. That also accounts for the mysterious blank line between "Letter" and "_2nd".

    You can get around this by enforcing some limits on what letter can be:
    Code:
    letter=0;
    while (!isprint(letter)) {
         scanf("%c",&letter);
    }
    or something to that effect.
    Consider this post signed

  3. #3
    Registered User hellork's Avatar
    Join Date
    Nov 2010
    Posts
    39

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help, scanf isn't waiting for user input
    By Blasz in forum C Programming
    Replies: 5
    Last Post: 05-07-2010, 05:32 AM
  2. Program Plan
    By Programmer_P in forum C++ Programming
    Replies: 0
    Last Post: 05-11-2009, 01:42 AM
  3. Need some help with C program writing
    By The_PC_Gamer in forum C Programming
    Replies: 9
    Last Post: 02-12-2008, 09:12 PM
  4. Basic C input output program help
    By trevordunstan in forum C Programming
    Replies: 2
    Last Post: 01-27-2008, 06:41 PM
  5. Limiting scanf input
    By SMurf in forum C Programming
    Replies: 0
    Last Post: 11-21-2002, 06:39 AM

Tags for this Thread