Thread: scanf , char, newline, space

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    17

    scanf , char, newline, space

    Hi, suppose I would use the following code (just the body, of course in reality I would also use the prinf function to communicate but I leaved that out of the code for simplicity)

    int a;
    int b;
    char c;
    scanf("%d", &a);
    scanf("%c", &c);
    scanf("%d", &b);

    Somehow the scanf function remembers the newline that gets there after entering integer a and uses that newline as the input for the second one.
    If however I would place a space like this then it works fine:

    int a;
    int b;
    char c;
    scanf("%d", &a);
    scanf(" %c", &c);
    scanf("%d", &b);

    I know that the scanf function isn't ideal for jobs like this but I just want to understand how it works, why does that space make the difference?
    My teacher did explain that that space would be nessecary to "eat up the newline" (unfortunately he chose to use english even though it is a foreign language to him).
    Can someone please make sense of this?

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    It's pretty simple really... look at what you are typing ...
    You enter ... 123 <return> ... for your first line
    The scanf() is looking for a number and consumes the 123 leaving <return> still in the input queue.
    Along comes the second scanf() which wants a character, it finds <return> which is a character and carries on.

    The space between the quotes and percent sign, simply tell scanf()'s internal code to ignore any "whitespace" so it skips over the <return> and waits for a new character.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. white space characters and scanf
    By bthomson900 in forum C Programming
    Replies: 4
    Last Post: 11-10-2010, 06:12 AM
  2. Remove newline char at the end
    By Ducky in forum C++ Programming
    Replies: 9
    Last Post: 12-23-2009, 02:29 PM
  3. Cin newline space problem... or something
    By Baqualish in forum C++ Programming
    Replies: 10
    Last Post: 10-17-2007, 03:49 AM
  4. scanf - strtok and space as delimiter?
    By Bill Cosby in forum C Programming
    Replies: 6
    Last Post: 09-20-2004, 06:45 PM
  5. How to use -- scanf to accept space?
    By leena_teoh in forum C Programming
    Replies: 4
    Last Post: 02-07-2002, 11:22 AM