Thread: while scanf loop

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    8

    while scanf loop

    hey im having a bit of trouble with this input loop. what is suposed to happen is its suposed to take a big list of 2 doubles on each line and then just print them out to prove they are being stored. but its not entering the loop at all as far as i can tell. any ideas to what im doing wrong??

    thanks

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void) {
      double a2 = 0.0;
      double a3 = 0.0;
      
      while (1 == scanf("%lg %lg", &a2, &a3)) {
        printf("%f %f", a2, a3);
      }
    
      return EXIT_SUCCESS;
    }

  2. #2
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    scanf returns the number of values it successfully read in - i.e. you
    should check for equity with 2, not 1
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  3. #3
    Registered User
    Join Date
    Sep 2005
    Posts
    8
    ah thanks mate

  4. #4
    Eager young mind
    Join Date
    Jun 2006
    Posts
    342
    fine that the problem has been solved.. but,there's always a danger of using scanf inside a loop that loops around many times.. I have come across isolated cases where the '\n' that gets stored after u hit enter in the first iteration will be read as the input in the second iteration.. Its always better to use fget() in a loop of this kind..

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    It has nothing to do with it being used in a loop that runs many times. It has to do with you not handling input correctly.


    Quzah.
    Hope is the first step on the road to disappointment.

  6. #6
    Eager young mind
    Join Date
    Jun 2006
    Posts
    342
    this actually came up when a group of us were having a discussion..
    The code was too simple

    Code:
       char option; 
       while(condition )
        {
            printf( "   .............diplays the various options  a,b,c, ..............\n");
            scanf("%c", &option);
       
            switch- case stuff 
             ...........
             various cases 
             ...........
            perfrom some operation on condition 
        }
    And his argument was that option was not getting changed anywhere , but still the prog was not working after the first loop.. So, some one came up with an idea that was similar to what i have written..if that is wrong ,please let me know...

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Like I said, it comes from you not handling input correctly. I know it's much easier to blame the function than it is for you to actually do it correctly, but it doesn't make it right. Just like it doesn't make it the function's fault that you're not using it correctly.


    Quzah.
    Hope is the first step on the road to disappointment.

  8. #8
    Eager young mind
    Join Date
    Jun 2006
    Posts
    342
    in that case.. well, i have brielfy described what the problem was.. can u say where was the input "wrongly" handled? It(option ) does not get changed during the looping process. The only place where it gets changed is with scanf()...

  9. #9
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    The input is wrongly handled because whenever you use
    scanf ("%c", &a_char) in a loop, you run the risk of reading in
    the newline character into a_char in the second iteration.
    I've written this small program to demonstrate this:

    Code:
    #include <stdio.h>
    
    int main(void)
    {
    	char a_char = 'a';
    
    	while (a_char != '.')
    	{
    		scanf ("%c", &a_char);
    		printf ("%c", a_char);
    	}
    
    	return 0;
    }
    what happens when I type a letter - say 'y'

    1. I see the character appear on screen
    2. I press enter
    3. The character is printed again via printf
    4. Somehow the cursor is moved below the character just shown:

    My console looks like this:

    y
    y
    d
    d
    e
    e

    ...
    Yet I didn't press enter twice, and the printf has no newline in it.
    Here's what is actually happening:

    4. I entered some letter other than '.', the looping condition is
    true, so scanf is called. It sees that there is a newline in the
    buffer so it reads that into a_char - and prints the newline.
    The loop starts over again, but this time there is nothing in the
    buffer, so I am prompted to enter information again.

    Interesting extension - this can be used to echo whatever you
    type - so if you type hello (obviously a series of characters), it will
    be printed out again as if you had read in an actual string and
    printed it out.

    In conclusion:

    1. scanf is fine if you use it to read in data other than strings (in
    which case fgets is far superior), but it will leave a newline in
    the buffer. When reading in indidvidual characters, be careful to
    not read in a newline inadvertently. It is generally a good idea
    to flush the buffer after using scanf, regardless of what type you
    are reading in.

    2. Calling getchar after a call to scanf usually causes problems for
    people unfamiliar with this behavior - I remember when I started
    out that I used to need 2 getchars to keep my console window
    open, but it only seemed to call it once - the first call was eating
    a newline. Resultingly, I now use a loop of getchar to flush the
    buffer of unwanted junk input and newlines
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  10. #10
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Use scanf intelligently and make it eat the newline as it does in this FAQ.
    http://c-faq.com/stdio/scanfhang.html

  11. #11
    Eager young mind
    Join Date
    Jun 2006
    Posts
    342
    thanks richie, nicely explained..

  12. #12
    Eager young mind
    Join Date
    Jun 2006
    Posts
    342
    hey, I just needed one more clarification on this..
    Suppose i do this :
    declare "option" as a pointer to char.. and at the start of each iteration i allcate mem to it, accept the value from the user, do whatever is reqd , and at the end of the loop, free the allocated region.. and repeat loop if necessary...
    This should also help in fixing the problem right?or will it?

  13. #13
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    I'm thinking you're overcomplicating something simple.

  14. #14
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    I can only see that idea causing more problems and solving
    nothing: If you want as much safety as possible, read input
    as a string, parse it with sscanf and flush the buffer. If sscanf
    fails, then generate error messages. This usually means more
    code than is necessary because most programs we see on this
    board are for personal use, so people can generally handle their
    own program crashing if they enter some crazy input. Just
    flushing the buffer at appropriate points will often work wonders.

    The problem is not particularly with the type of variable you are
    writing data into, but rather not cleaning up the buffer after you.
    Pointers, memory allocation is not addressing this at all.

    Quote Originally Posted by quzah
    It has to do with you not handling input correctly.
    Exactly, as usual!
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Stopping an Infinite Loop
    By linuxpyro in forum C Programming
    Replies: 4
    Last Post: 11-30-2006, 12:21 PM
  2. Help with a simple loop...
    By Optimus Prime in forum C Programming
    Replies: 18
    Last Post: 11-11-2006, 09:28 AM
  3. I can't get out of my while loop!!
    By panfilero in forum C Programming
    Replies: 2
    Last Post: 11-20-2005, 04:52 AM
  4. Caught in a Loop
    By aprilbiz in forum C Programming
    Replies: 16
    Last Post: 07-22-2002, 06:06 PM
  5. How to change recursive loop to non recursive loop
    By ooosawaddee3 in forum C Programming
    Replies: 1
    Last Post: 06-24-2002, 08:15 AM