Using Gets with typedef Struct

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

  1. macrumors newbie

    Sep 5, 2010

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

    gets(,20); is a typedef struct. I get an error message "Too many arguments to function 'gets'. "

    How can I use gets with a struct?


    Paul B.
  2. macrumors 68040

    Feb 2, 2008
    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 is a char array you can call fgets() like this:

    fgets(, 20, stdin);
  3. thread starter macrumors newbie

    Sep 5, 2010


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


    Paul B.
  4. macrumors 603


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

    Mar 29, 2009
    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