Using Gets with typedef Struct

Discussion in 'Mac Programming' started by pbyrne98, Sep 5, 2010.

  1. macrumors newbie

    Joined:
    Sep 5, 2010
    #1
    Hi,

    I'm going through HowTo in C programming and the following code is given :

    gets(s.name,20);

    s.name is a typedef struct. I get an error message "Too many arguments to function 'gets'. "

    How can I use gets with a struct?

    cheers,

    Paul B.
     
  2. macrumors 68040

    Joined:
    Feb 2, 2008
    #2
    That is because gets only take one argument, no size arg for gets. The call will work like expected if you only ad an f to gets() meaning fgets() but you then need to specify from where the string is coming, in this case stdin. That is the better function to use, since there is no way to call gets() safely. So use fgets() and it should work.

    If s.name is a char array you can call fgets() like this:

    Code:
    fgets(s.name, 20, stdin);
    
     
  3. thread starter macrumors newbie

    Joined:
    Sep 5, 2010
    #3
    Thanks

    Hi,

    Thanks for that, it works. Just don't know why they put it in the HowTo tutorial.

    cheers,

    Paul B.
     
  4. macrumors 603

    Cromulent

    Joined:
    Oct 2, 2006
    Location:
    The Land of Hope and Glory
    #4
    Never ever use gets().
     
  5. macrumors 68000

    Joined:
    Mar 29, 2009
    Location:
    USA
    #5
    It may just not be proofread. Get one of the recommended books on C ;)

    Specifically, from the C FAQ:

    Q: Why does everyone say not to use gets()?

    A: Unlike fgets(), gets() cannot be told the size of the buffer it's to read into, so it cannot be prevented from overflowing that buffer if an input line is longer than expected--and Murphy's Law says that, sooner or later, a larger-than-expected input line will occur. [footnote] (It's possible to convince yourself that, for some reason or another, input lines longer than some maximum are impossible, but it's also possible to be mistaken, [footnote] and in any case it's just as easy to use fgets.)

    The Standard fgets function is a vast improvement over gets(), although it's not perfect, either. (If long lines are a real possibility, their proper handling must be carefully considered.)

    One other difference between fgets() and gets() is that fgets() retains the '\n', but it is straightforward to strip it out. See question 7.1 for a code fragment illustrating the replacement of gets() with fgets().
     

Share This Page