Thread: Do While Character Input Error

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    1

    Do While Character Input Error

    My code isn't allowing me to input a character after I input a number.

    Code:
    #include <stdio.h>
    #include <string.h>
    int main (void)
    {
    	char choice;
    	int num;
    	
    	do
    	{
    		
    		
    		printf("enter a number: \n");
    		scanf("%d",&num);
    		
    		
    		printf("enter another? \n");
    		scanf("%c",&choice);
    		
    		
    		
    	}while (choice!='y'||choice!='Y');
    	
    	return 0;	
    }

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    you should have search forum - this question is been answered once a week...

    scanf formats like %s, %d etc leave everything that is not parsed in the input stream - in your case %d format leaves \n character

    %c format does not skip anything - so it reads \n character left from the previous scanf and puts it into the choice variable

    so you need to flush the buffer from what is left there before calling the second scanf

    How to do it - search forum or FAQ, there is a lot of samples of that procedure (just do not call fflush as it is undefined for input streams)
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    Quote Originally Posted by crackpat View Post
    My code isn't allowing me to input a character after I input a number.

    Code:
    #include <stdio.h>
    #include <string.h>
    int main (void)
    {
    	char choice;
    	int num;
    	
    	do
    	{
    		
    		
    		printf("enter a number: \n");
    		scanf("%d",&num);
    		
    		
    		printf("enter another? \n");
    		scanf(" %c",&choice);//modified here(space befor %c)
    		
    		
    		
    	}while (choice!='y'||choice!='Y');
    	
    	return 0;	
    }
    i've modified your code.this will also work.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. Quantum Random Bit Generator
    By shawnt in forum C++ Programming
    Replies: 62
    Last Post: 06-18-2008, 10:17 AM
  3. Making C DLL using MSVC++ 2005
    By chico1st in forum C Programming
    Replies: 26
    Last Post: 05-28-2008, 01:17 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM