Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

pbyrne98

macrumors newbie
Original poster
Sep 5, 2010
2
0
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.
 
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);
 
Thanks

Hi,

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

cheers,

Paul B.
 
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().
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.