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

  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
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    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
    86
    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 12:58 PM.
    V8 Interceptor: KDE 5.25.5 on Manjaro Linux 22.0.0 "Sikaris"
    Steering wheel: gcc 12.2.0 in Kate
    Supercharger: NASM 2.15.05
    Engine: AMD Ryzen 7 1700
    Dashboard: NVIDIA GeForce GTX 1060 6GB
    Rusty old trailer for hauling 3% of my Steam catalog: Windows 7 Pro 64bit SP1
    3 Antique Ford Model T automobiles for vintage LAN gaming: Windows XP SP3
    Sturdy buckboard for DOS LAN gaming: DOSBox 0.74-3 on Windows XP SP3

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