Thread: Why does my program only continue on hitting a key + Enter

  1. #1
    Registered User
    Join Date
    May 2012
    Posts
    4

    Why does my program only continue on hitting a key + Enter

    Hi,
    Can someone tell me why this (otherwise working) program isnt continuing all by its own, but only when I hit a key and Enter?
    Thanks
    Attached Files Attached Files

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    In the following line:
    Code:
    scanf("%d\n", &n);
    Because you included the newline character in scanf() you must enter that character complete the function.

    Jim

  3. #3
    Registered User
    Join Date
    Mar 2010
    Posts
    583
    Yep. From scanf documentation: scanf - C++ Reference

    Whitespace character: the function will read and ignore any whitespace characters (this includes blank spaces and the newline and tab characters) which are encountered before the next non-whitespace character. This includes any quantity of whitespace characters, or none.
    Scanf won't start trying to match the pattern until the first time you hit enter. "%d\n" will match the number and the newline, but then due to the above quote, it'll keep matching whitespace until you put a non whitespace character in (another key and enter).

    Very irritating, I hate scanf.

    If you just use %d, a newline will be left waiting on stdin and will mess up subsequent user inputs. You can getchar() it after the scanf, or you could read a char in scanf and throw it away (see * in the link).

  4. #4
    Registered User
    Join Date
    May 2012
    Posts
    4
    Thanks a lot to both of you Jim and smokeyangel!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Close console without hitting enter
    By Cathalo in forum C++ Programming
    Replies: 5
    Last Post: 05-02-2009, 08:32 AM
  2. reading input w/o hitting enter?
    By Aalmaron in forum C Programming
    Replies: 1
    Last Post: 01-31-2006, 10:38 PM
  3. Help with hitting 'enter'
    By K-Zodron in forum C++ Programming
    Replies: 4
    Last Post: 06-02-2005, 08:20 AM
  4. Console Window Dissapears after hitting Enter
    By Sentral in forum C++ Programming
    Replies: 5
    Last Post: 05-29-2005, 02:30 PM
  5. Hitting enter while FOCUS on an EDIT
    By Garfield in forum Windows Programming
    Replies: 8
    Last Post: 09-02-2003, 10:26 AM