Jump to content

too few arguments to function ‘fgets’

- - - - -

  • Please log in to reply
5 replies to this topic

#1
theCnewbie

theCnewbie

    Newbie

  • Members
  • Pip
  • 1 posts
so I'm reading C for dummies, and am asked to write this code, when I go to compile it I get:

insult1.c:8: error: too few arguments to function ‘fgets’

#include <stdio.h>


int main()

{

	char jerk[20];


	printf("Give the name of a jerk you know");

	fgets(jerk);

	printf("Yeah i know %s I think he's a jerk too",jerk);

	return(0);

}

what am I doing wrong?

#2
dbug

dbug

    Programmer

  • Members
  • PipPipPipPip
  • 155 posts
If you look at the manual for fgets function you will see that it requires 3 arguments:

char *fgets(char *s, int size, FILE *stream);
The first parameter is where the typed name will go (the jerk variable). The second one says how many characters it can read. Here you must use the size of jerk variable as a maximum (you can use the keyword sizeof() to let the compiler determine the maximum size). The last parameter must indicate from where you want to read the data. If you want to read from the keyboard, you must use stdin (it is the standard input channel).

fgets(jerk, sizeof(jerk), stdin);


#3
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
@dbug, fgets(jerk, 20, stdin) would be better to avoid any overflow (accept 19 + 1 null into char[20])

EDIT: Whoops, did not read that properly.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#4
dbug

dbug

    Programmer

  • Members
  • PipPipPipPip
  • 155 posts
Isn't that what I said ? :confused:

I used sizeof(jerk) to be more flexible, but (in this case) it's the same than writing 20. Have I missed something ?

#5
krwq

krwq

    Newbie

  • Members
  • PipPip
  • 28 posts
he means
fgets(jerk, sizeof(jerk)-1, stdin);


#6
dbug

dbug

    Programmer

  • Members
  • PipPipPipPip
  • 155 posts
No, fgets(str, size, stream) reads at most size - 1 characters from stream. It reserves the last char to write a terminating null character.

If you use fgets(jerk, 20, stdin), it will read, at most, 19 characters from stdin.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users