How to get a y or n answer without the newline character

This is a discussion on How to get a y or n answer without the newline character within the C Programming forums, part of the General Programming Boards category; How can I get a y or n answer from the user without messing with newline character. The following code ...

  1. #1
    Registered User
    Join Date
    Jul 2010
    Posts
    37

    How to get a y or n answer without the newline character

    How can I get a y or n answer from the user without messing with newline character.
    The following code fails in this because the second getchar gets the newline character from the previous answer:

    Code:
    do {
    		result = play_game();
    		if (result == true)
    		{
    			printf("\nYou win!");
    			wins++;
    			printf("\n\nPlay again?");
    			ch = getchar();
    		}
    		else
    		{
    			printf("\nYou lose!");
    			losses++;
    			printf("\n\nPlay again?");
    			ch = getchar();
    		}
    	} while (ch != 'n');
    Thank you.

  2. #2
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,650
    Code:
    void flush_input_buffer(void)
    {
        int c;
        while ((c = getchar()) != '\n') ;
    }
    call flush_input_buffer() after receiving input to remove anything left over up to and including the newline character.

  3. #3
    Codus Conjectus spongefreddie's Avatar
    Join Date
    Sep 2010
    Location
    USA
    Posts
    82
    This is something I use, but I'm not sure how proper it is, since I'm still a newbie.

    Code:
    while (getchar() != '\n')
       continue;
    It's pretty much the same as rags_to_riches' answer, but his is probably better, because it's a function you can call.
    Last edited by spongefreddie; 11-12-2010 at 11:58 AM.
    Steering Wheel: gcc in Code::Blocks 10.05
    Batmobile: Linux Mint 14, running kernel 3.5 and KDE 4.9.2
    Engine: AMD FX-8350 Vishera 8-core
    Dashboard: NVIDIA GTX 570 HD
    Rusty old trailer for hauling games: Windows XP SP3 (in VirtualBox)
    ORV for composing music: Windows 7 Pro 64bit (in VirtualBox)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem storing a newline character
    By mdekom12 in forum C Programming
    Replies: 8
    Last Post: 04-25-2010, 10:51 PM
  2. Checking to see if a string is just a newline character
    By Beowolf in forum C++ Programming
    Replies: 3
    Last Post: 11-14-2007, 08:29 PM
  3. Tic Tac Toe program...
    By Kross7 in forum C++ Programming
    Replies: 12
    Last Post: 04-12-2007, 03:25 PM
  4. syntax error when defining vectors
    By starkhorn in forum C++ Programming
    Replies: 5
    Last Post: 09-22-2004, 12:46 PM
  5. comparing int to newline character
    By RedZippo in forum C++ Programming
    Replies: 5
    Last Post: 05-13-2004, 06:37 PM

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