Thread: Beginner Question

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    9

    Beginner Question

    What is the difference between gets() and scanf?
    When should i use gets() or scanf?

    Thank!

  2. #2
    Registered User
    Join Date
    Mar 2003
    Posts
    143
    The best way is to use fgets() followed by sscanf() eg:
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    int main (void)
    {
      char buf[BUFSIZ];
      int input[2];
    
      do {
        printf("enter two numbers: ");
        fflush(stdout);
        fgets(buf, sizeof(buf), stdin);
      } while (sscanf(buf, "%d %d", &input[0], &input[1]) != 2);
    
      printf("you typed: %d %d\n", input[0], input[1]);
    
      return 0;
    }
    For reasons why this is better see the FAQs
    DavT
    -----------------------------------------------

  3. #3
    Registered User
    Join Date
    Mar 2004
    Posts
    9
    But i though fget() is for file, not standard input, scanf is for standard input?

    Am i right?

    Thank

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    stdin is a file stream. Thus, any function which is meant for input streams, can be used on stdin. The same holds for the standard output stream. Any function meant for output can be applied to it. fputs, fputc, fprintf and the like.

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

  5. #5
    Registered User
    Join Date
    Mar 2004
    Posts
    9
    For the below code, post by DavT:

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    int main (void)
    {
      char buf[BUFSIZ];
      int input[2];
    
      do {
        printf("enter two numbers: ");
        fflush(stdout);
        fgets(buf, sizeof(buf), stdin);
      } while (sscanf(buf, "%d %d", &input[0], &input[1]) != 2);
    
      printf("you typed: %d %d\n", input[0], input[1]);
    
      return 0;
    }

    I don't really understand how it work, it look very hard, or it is just me that's poor. Why fgets() and sscanf() and not just one of the both?

    I alway code it like this:


    Code:
    int main (void)
    {
      int input1, input2;
      
      printf("enter two numbers: ");
      scanf("%d %d", &input1, &input2);
    
      printf("you typed: %d %d\n", input1, input2);
    
      return 0;
    }
    What is the different? Am i all along doing the wrong thing?!

  6. #6
    Registered User
    Join Date
    Mar 2003
    Posts
    143
    To quote myself... "For reasons why this is better see the FAQs".
    But since you probably still won't bother, the short reason is that
    scanf() leaves the LF so if you do another scanf() you won't necessarily
    get what you expect. At the risk of repeating myself, read the FAQs
    DavT
    -----------------------------------------------

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > Why fgets() and sscanf() and not just one of the both?
    scanf() handles both input and conversion, so it has to return both input errors and conversion errors.
    When things go wrong, the input stream is in a pretty undefined state, you've no real idea of what chars have been used and what chars remain.

    fgets() is purely input. You know exactly what has been read, and what hasn't in the case of error.
    sscanf() is purely conversion. Any failure here won't make a mess of your attempts at further input. Additionally, since you're reading from some memory location you can potentially have several attempts at trying to decode the same buffer (you can't do this with scanf at all).

    > What is the different? Am i all along doing the wrong thing?!
    You can make fgets+sscanf robust
    scanf is only suitable for throwaway programs only you will use
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    essence of digital xddxogm3's Avatar
    Join Date
    Sep 2003
    Posts
    589
    I just want to make sure I'm understanding this code correctly as well. Please check my comments for accuracy in interpretation and for clarification of my question. Thanks

    Code:
    #include <stdlib.h>
    #include <stdio.h>
     
    int main (void)
    {
    char buf[BUFSIZ];
    int input[2];
     
    do {
    	printf("enter two numbers: ");
    	fflush(stdout);
     
    /*flushes the buffer due to multiple loops 
    and the possibility of multiple inputs.*/
     
    	fgets(buf, sizeof(buf), stdin);
     
    /* get from keyboard and place in memory 
    addressed by buf and size of buf. */
     
    } while (sscanf(buf, "%d %d", &input[0], &input[1]) != 2);
     
    /*loop exit test. if sscanf returns two successful 
    items of data, then exit. Place data from buff into 
    array locations addressed by input. 
    Question: does this exit after two letters are 
    intered in sequentially, or does it exit upon 
    hitting two keys at once? I do not have a 
    compiler to test this. */ 
     
    printf("you typed: %d %d\n", input[0], input[1]);
     
    return 0;
    }
    Last edited by xviddivxoggmp3; 04-27-2004 at 11:37 AM.
    "Hence to fight and conquer in all your battles is not supreme excellence;
    supreme excellence consists in breaking the enemy's resistance without fighting."
    Art of War Sun Tzu

  9. #9
    Ultraviolence Connoisseur
    Join Date
    Mar 2004
    Posts
    555
    Quote Originally Posted by xviddivxoggmp3
    Code:
    	printf("enter two numbers: ");
    	fflush(stdout);
    
    /*flushes the buffer due to multiple loops 
    and the possibility of multiple inputs.*/
    Not exactly.....stdout is by default buffered, so it wont print anything until it reaches a \n (newline character) fflush prints everything thats in the buffer.

    } while (sscanf(buf, "%d %d", &input[0], &input[1]) != 2);
    /*loop exit test. if sscanf returns two successful
    items of data, then exit. Place data from buff into
    array locations addressed by input. Question: does
    this exit after two letters are intered in sequentially,
    or does it exit upon hitting two keys at once? I do
    not have a compiler to test this. */
    sscanf will return 2 when two items are entered with a space seperating them. like this:

    enter two numbers: 2 2

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    If the user enters EOF (ctrl-z in DOS/Console, ctrl-d in unix/linux), the code will loop forever
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  11. #11
    essence of digital xddxogm3's Avatar
    Join Date
    Sep 2003
    Posts
    589
    I've read that stdout is similar to a stream pointer to a file.
    Is this a correct depiction?
    It is listed in a group that also includes stdin and stderr.
    I read also that fflush, flushes buffers.
    Why would fflush(stdout) print.
    I again do not have a compiler, so I'm unable to experiment with the code.
    So you are saying that the combination of an output stream and buffer flush will
    create a result similar to a printf statement on a string?
    I'm not trying to make you repeat yourself, and I do appologize for the elementry
    nature of the question.
    "Hence to fight and conquer in all your battles is not supreme excellence;
    supreme excellence consists in breaking the enemy's resistance without fighting."
    Art of War Sun Tzu

  12. #12
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Regarding fflush(stdout), there is some more information here and here. But essentially, prompts that don't end with a newline may or may not be seen. The fflush(stdout) encourages it.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  13. #13
    essence of digital xddxogm3's Avatar
    Join Date
    Sep 2003
    Posts
    589
    Hello Dave,

    Nice to see you again.
    The second link you posted is not working.
    I'm not sure if it is me or if the link is broken.

    New questions:
    (1) In the example we are reviewing
    fflush(stdio), does stdio count as a generic pointer to buf, or does it just clean the keybord input stream and print the stored data?

    (2) Does fflush(stdio) echo the inputed data to the screen immediately after keyed, or does it wait for the return to be depressed, before processing and printing?

    Please correct me if I'm way off the mark.
    I just want to acquire a better understanding of the issue. And I do appologize if I'm diverting the topic of the thread. If it helps, can a moderater move the post at the point that I jumped in to a new post called fflush(stdio)?

    Thanks.
    X
    Last edited by xviddivxoggmp3; 04-27-2004 at 03:08 PM.
    "Hence to fight and conquer in all your battles is not supreme excellence;
    supreme excellence consists in breaking the enemy's resistance without fighting."
    Art of War Sun Tzu

  14. #14
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    >The second link you posted is not working.

    Hmm. Maybe this?

    >fflush(stdio)

    fflush(stdout) - stdout is the standard output stream.

    Code:
    do {
       printf("enter two numbers: ");
       /* at this point, there may or may not be any visible prompt */
       fflush(stdout); /* this encourages it to be made visible */
       /* the next line will gather characters until the return key is pressed */
       fgets(buf, sizeof(buf), stdin);
    Without fflush(stdout), you may see a prompt or you may see a blank line.
    (1) In the example we are reviewing
    fflush(stdio), does stdio count as a generic pointer to buf, or does it just clean the keybord input stream and print the stored data?
    There is no stdio. You can fflush stdout to encourage the host to present the data sent to it. You can't fflush stdin because the standard input stream is an input stream, and behavior is undefined for fflush on an input stream.

    (2) Does fflush(stdio) echo the inputed data to the screen immediately after keyed, or does it wait for the return to be depressed, before processing and printing?
    Keyed? Return key?

    My impression is that printf, et. al. do not write to the 'display': instead they write to the stdout, which is realized as some buffer. When the host is damn good and ready, it presents the buffer contents to the 'display'. The host is quite likely to do this after it sees a newline. But if it doesn't see a newline, it may just choose to wait a while. Adding the fflush(stdout) tells the host you'd like it to be shown now.

    [This is a lot less technical than the link I tried to post, and my wording has been less than clear lately...]
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  15. #15
    essence of digital xddxogm3's Avatar
    Join Date
    Sep 2003
    Posts
    589
    oops it should have been fflush(stdout). I have the habit of using stdio for my header file.
    a case of my fingers typing and my brain not working. I understand a little better now that i have research and read on the topic. It is weird how endl, flush() and fflush() are nothing alike.
    Last edited by xviddivxoggmp3; 04-28-2004 at 03:55 PM.
    "Hence to fight and conquer in all your battles is not supreme excellence;
    supreme excellence consists in breaking the enemy's resistance without fighting."
    Art of War Sun Tzu

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Beginner: Linked List question
    By WeatherMan in forum C++ Programming
    Replies: 2
    Last Post: 04-03-2008, 07:16 AM
  2. Quick IF statement question (beginner)
    By jim.rattlehead in forum C Programming
    Replies: 23
    Last Post: 11-29-2007, 06:51 AM
  3. beginner question
    By Barrot in forum C++ Programming
    Replies: 4
    Last Post: 08-19-2005, 02:17 PM
  4. Question About External Files (Beginner)
    By jamez05 in forum C Programming
    Replies: 0
    Last Post: 08-11-2005, 07:05 AM
  5. Beginner on Win32 apps, lame question.
    By Templario in forum C Programming
    Replies: 3
    Last Post: 11-06-2002, 08:39 PM