Thread: problem with scanf() function

  1. #1
    Registered User
    Join Date
    Mar 2017
    Posts
    2

    problem with scanf() function

    Here's the deal, if let's say i declare a integer and a character:

    int x;
    char c;

    Now if I do this:

    scanf ("%c", &c);
    scanf("%d", &x);

    everything's fine, I input c and then input x.
    BUT if i scan x first:

    scanf("%d", &x);
    scanf ("%c", &c);

    there's a problem. when i build and run program terminates without scanning c. second statement is not executed. WHY?

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    This happens because newline is a character too. To avoid this "problem", put a space before the %c, like this:
    Code:
    scanf(" %c", &c);
    the space tells scanf() to ignore all white-space characters.
    Devoted my life to programming...

  3. #3
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,127
    First of all you should show a small working program that we can test, and show input and output.

    Now as for the second example, what makes you think it did not work?

    If I entered 10 as the input to the first scanf(), x would contain 10, and the newline would be left in the input buffer. Then c would contain the next character in the buffer, the newline left from the first scanf()! It worked as it should have.

    To get what YOU expected, you would need to clean out the input buffer with the following statement, before getting a char into c:
    Code:
    while ((ch = getchar()) != '\n' && ch != EOF);
    EDIT: NEVER, NEVER use fflush() on an input buffer! fflush() is ONLY for output buffers!

    Yes, GReaper is correct, but the above code is a better solution, for most cases.
    Last edited by rstanley; 03-09-2017 at 09:45 AM.

  4. #4
    Registered User
    Join Date
    Mar 2017
    Posts
    2
    thx i better use a simpler solution because i'm a beginner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. while function with scanf function confusion
    By yukapuka in forum C Programming
    Replies: 7
    Last Post: 08-08-2012, 03:49 AM
  2. Function definition problem with scanf()
    By twazzler in forum C Programming
    Replies: 2
    Last Post: 04-16-2011, 09:16 AM
  3. Creating an scanf function inside an function
    By anserudd in forum C Programming
    Replies: 4
    Last Post: 03-25-2011, 09:19 AM
  4. problem with scanf function
    By lida in forum C Programming
    Replies: 2
    Last Post: 12-16-2008, 11:22 AM
  5. Newbie problem with scanf function...
    By Mithal in forum C Programming
    Replies: 1
    Last Post: 11-13-2005, 10:28 PM

Tags for this Thread