Do While Character Input Error

This is a discussion on Do While Character Input Error within the C Programming forums, part of the General Programming Boards category; My code isn't allowing me to input a character after I input a number. Code: #include <stdio.h> #include <string.h> int ...

  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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,470
    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)
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  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, 02: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21