Thread: Is this code snippet wrong

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    3

    Is this code snippet wrong

    i want this code to keep executing until i enter 'n'. it sort of work in the sense that the loop exit when i enter 'n' and the first loop is executed ok but when i enter 'y' the two print statement is printed twice on the output.

    Code:
    #include <stdio.h>
    
    
    int main()
    {
        char a='y';
        while(a!='n')
        {
                     printf("testing testing testing");
                     printf("do you want to continue y or n");
                     scanf("%c",&a);
        }
    }

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    When you type 'y' and enter, you are actually sending two characters - 'y' and newline. The newline is consumed the second time through the loop, making appear as if the scan is being ignored every other time. You can make your "scanf()" call ignore whitespace (i.e. the newline) by putting a single space directly before the %c.

    Code:
    scanf(" %c",&a);
    More information on this here: FAQ > How do I avoid a "dangling" newline when reading single character user input? - Cprogramming.com
    Last edited by Matticus; 01-15-2014 at 09:46 AM.

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Enter-key is a character too. If you don't want to read enter-key, you need to change your scanf so that it will skip enterkey:
    Code:
    scanf(" %c", &a);

  4. #4
    Registered User
    Join Date
    Jan 2014
    Posts
    3
    thanks Matticus, much appreciated.

  5. #5
    Registered User
    Join Date
    Jan 2014
    Posts
    3
    thanks tabstop, much appreciated.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. what will be the output of this code snippet
    By devilofwar in forum C Programming
    Replies: 12
    Last Post: 12-13-2010, 05:41 PM
  2. Explanation of code snippet
    By Jelte in forum C++ Programming
    Replies: 1
    Last Post: 01-20-2010, 06:59 AM
  3. C code snippet which I need help understanding
    By c_me in forum C Programming
    Replies: 3
    Last Post: 07-28-2006, 06:06 AM
  4. Why is this code snippet refusing to work ?
    By saraghav in forum C Programming
    Replies: 4
    Last Post: 06-01-2006, 03:25 AM
  5. a great little code snippet...
    By skeptik in forum Windows Programming
    Replies: 1
    Last Post: 09-24-2002, 11:45 PM