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

  1. #1
    Registered User
    Join Date
    Jul 2010

    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:

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

  2. #2
    Join Date
    Dec 2007
    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
    This is something I use, but I'm not sure how proper it is, since I'm still a newbie.

    while (getchar() != '\n')
    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 12:58 PM.
    Steering Wheel: gcc in Code::Blocks 13.12
    Batmobile: Linux Mint 17.2 Cinnamon 64-bit, running kernel 3.16.0
    Engine: AMD FX-8350 Vishera 8-core
    Dashboard: NVIDIA GTX 570 HD
    Rusty old trailer for hauling games: Windows XP SP3
    ORV for composing music: Windows 7 Pro 64bit

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