77Views6Replies

Author Options:

Why won't this compile? Answered

I am going by a book to teach me C programming, and I have entered the program exactly, but my compiler says there's an error.  I know it is not an issue with the compiler/IDE because I tested it in another compiler and had the same result.

Here is the code:
#include <stdio.h>
#include <string.h>
int main (void)
{
    char buffer[256];

    printf("Enter your name and press <Enter>:\n");
    fgets( buffer );

    printf("\nYour name has %d characters and spaces!", strlen(buffer));

    return 0;
}

It says on line 8 (the one with fgets) that there are too few arguments, yet the book says it should compile correctly.  The book is Sams Teach Yourself C Programming, and it is in lesson 2 exercise 5.

Thank you for any help!

Discussions

0
None
mh76dk

Best Answer 5 years ago

fgets() will read from a file (your missing arguments), you should probably use gets() instead.

See for example http://www.tutorialspoint.com/c_standard_library/c_function_gets.htm vs. http://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm

0
None
mh76dkStarscreamClone

Answer 5 years ago

Good to hear. (such mistakes in books are really really annoying, have you checked the Sams site for an Errata? Might save you another headache)

0
None
mpilchfamily

5 years ago

Why are there spaces before and after Buffer on line 8? Think if you leave the spaces out you may find it works. These small sytax deals are always the things that throw the compiler for a loop.

0
None
mh76dkmpilchfamily

Answer 5 years ago

Whitespace is pretty much irrelevant in C. And the "function( arg1, arg2 );" style is not uncommon to see - the argument being that it is easier to read than "function(arg1,arg2);".

0
None
StarscreamClonempilchfamily

Answer 5 years ago

I actually found that it was the f in fgets() was the issue, thanks to the first comment here; I previously tried without the spaces before and after buffer, so it wasn't a problem.