PDA

View Full Version : Using Gets with typedef Struct




pbyrne98
Sep 5, 2010, 07:20 AM
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.



subsonix
Sep 5, 2010, 07:38 AM
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:


fgets(s.name, 20, stdin);

pbyrne98
Sep 5, 2010, 08:17 AM
Hi,

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

cheers,

Paul B.

Cromulent
Sep 5, 2010, 08:23 AM
Never ever use gets().

robvas
Sep 5, 2010, 11:34 AM
Thanks for that, it works. Just don't know why they put it in the HowTo tutorial.


It may just not be proofread. Get one of the recommended books on C ;)

Never ever use gets().

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().